获取当前时间戳及日期
import time
import datetime
# time获取当前时间
now = int(time.time()) # 1595314814
time_array = time.localtime(now)
date = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
print(date) #2020-07-21 15:00:57
# datetime获取当前时间
now = datetime.datetime.now() # 1595314817
date = now.strftime("%Y-%m-%d %H:%M:%S")
print(date) #2020-07-21 15:01:00
字符串类型的日期转时间戳格式
import time
# 字符类型的时间
date = '2020-07-21 15:00:00'
# 转为时间数组
time_array = time.strptime(date, "%Y-%m-%d %H:%M:%S")
print(time_array)
#time.struct_time(tm_year=2020, tm_mon=7, tm_mday=21, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=203, tm_isdst=-1)
# time_array可以调用里面的参数
print(time_array.tm_year) # 2020
print(time_array.tm_mon) # 7
print(time_array.tm_mday) # 21
# 转为时间戳
timestamp = int(time.mktime(time_array))
print(timestamp) # 1595314800
# 转为其它显示格式
other_show_time = time.strftime("%Y/%m/%d %H:%M:%S", time_array)
print(other_show_time) # 2020/07/21 15:00:00
时间戳转换为字符串类型的日期
import time
import datetime
# 使用time
timestamp = 1595314800
time_array = time.localtime(timestamp)
date = time.strftime("%Y-%m-%d %H:%M:%S", time_array)
print(date) # 2020-07-21 15:00:00
# 使用datetime
date_array = datetime.datetime.fromtimestamp(timestamp)
date = date_array.strftime("%Y-%m-%d %H:%M:%S")
print(date) # 2020-07-21 15:00:00
# 使用datetime(utc时间、相差8小时)
date_array = datetime.datetime.utcfromtimestamp(timestamp)
date = date_array.strftime("%Y-%m-%d %H:%M:%S")
print(date) # 2020-07-21 07:00:00