1、时间戳转换格式化时间
import time def timestamp_to_str(timestamp=None,format='%Y-%m-%d %H:%M:%S'): '''这个是把时间戳转换成格式化好的实际,如果不传时间戳,那么就返回当前的时间''' if timestamp: return time.strftime(format,time.localtime(timestamp)) else: return time.strftime(format,time.localtime()) print(timestamp_to_str(1554307200,'%Y-%m-%d')) print(timestamp_to_str(format='%Y-%m-%d')) print(timestamp_to_str()) /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 /Users/dongyf/Documents/python/besttest_study/test.py 2019-04-04 2019-06-23 2019-06-23 21:45:49
2、格式化时间转换时间戳
import time def str_to_timestamp(str=None,format='%Y-%m-%d %H:%M:%S'): # 格式化好的时间转时间戳的,如果不传格式化好的时间,就返回当前的时间戳 if str: return int(time.mktime(time.strptime(str,format))) else: return int(time.time()) print(str_to_timestamp()) print(str_to_timestamp('2019-04-04 12:12:34')) print(str_to_timestamp('2019-07-09','%Y-%m-%d')) /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 /Users/dongyf/Documents/python/besttest_study/test.py 1561298040 1554351154 1562601600