获取当前时间:
# 获取当前10位时间戳,默认返回为float类型
print int(time.time()) # output: 1561790808
# 获取当前13位时间戳,默认返回为float类型
print int(time.time() * 1000) # output: 1561790808517
# 获取当前时间元组,属性分别为当前年,月,日,时,分,秒,当周第几天,当年第几天,是否夏令时
# 可直接用.调用属性(如:time.localtime().tm_year)
# 可接受时间戳参数进行转换
print time.localtime() # output: time.struct_time(tm_year=2019, tm_mon=6, tm_mday=29, tm_hour=14, tm_min=58, tm_sec=17, tm_wday=5, tm_yday=180, tm_isdst=0)
# datetima模块
print datetime.datetime.now() # output: 2019-06-29 15:34:03.184000
按需求格式化时间(日期格式化符号对照表链接):
# time模块
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # output:2019-06-29 14:59:57
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) # output:Sat Jun 29 14:59:57 2019
# datetime模块
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # output:2019-06-29 14:59:57
# ISO格式时间
print datetime.datetime.now().isoformat() # output: 2019-06-29T15:39:55.599000
时间戳与字符串格式相互转换:
# 字符串转时间戳
a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")) # output:1459175064.0 (float类型)
# 时间戳转字符串
a = 1459175064.0
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(a)) # output:2016-03-28 22:24:24
时间加减计算:
# timedalta构造函数:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
print datetime.datetime.now().day # output:29
print datetime.datetime.now()-datetime.timedelta(days=1) # output:2019-06-28 15:48:23.451000