时间转换与加减
目录
import time
import datetime
localtime = time.asctime(time.localtime(time.time()))
print(localtime) # Sun Jul 5 17:14:09 2020
time
# 当前时间戳
time_stamp = time.time() # 1381419600
# 时间戳 => time结构体
time_array = time.localtime(time_stamp)
# 字符串 => time结构体
time_array = time.strptime('2020-10-19 00:00:00', '%Y-%m-%d %H:%M:%S')
# 时间戳 => 时间格式字符串
format_str = "%Y-%m-%d %H:%M:%S"
format_time = time.strftime(format_str, time.localtime(time_stamp))
print(format_time) # 2013-10-10 23:40:00
# 时间格式字符串 => 时间戳
time_str = '2020-10-19 00:00:00'
time_stamp = time.mktime(time.strptime(time_str, format_str))
print(time_stamp) # 1381419600
datetime
# 当前时间 datetime结构体
now = datetime.datetime.now()
now_date = datetime.datetime.now().date()
# datetime结构体 => 字符串
# print(str(now_date)) # '2021-10-31'
format_time = now.strftime("%Y-%m-%d %H:%M:%S") # '2021-10-31 18:13:21'
# 字符串 => datetime结构体
time_str = '2021-10-31'
date_array = datetime.datetime.strptime(time_str, '%Y-%m-%d').date()
# 日期加减
next_day = now + datetime.timedelta(days=7)
days = (next_day - now).days