Python 简单的时间处理
Python 简单的时间处理
目前主要总结time
和datetime
两个模块的处理
1.时间戳和格式化时间字符串间的转换
import time
from datetime import datetime
1.1 获取时间戳
timestamp1 = time.time()
print('timestamp1: ', timestamp1)
timestamp2 = datetime.now().timestamp()
print('timestamp2: ', timestamp2)
timestamp1: 1617629283.7287312
timestamp2: 1617629283.728771
返回值类型为float
1.2 时间戳转格式化时间字符串
日期格式通常为 年-月-日 时:分:秒,对应的字符串格式就是%Y-%m-%d %H:%S:%M
date1 = time.localtime(timestamp1)
format_time1 = time.strftime('%Y-%m-%d %H:%S:%M', date1)
print('format_time1: ', format_time1)
date2 = datetime.fromtimestamp(timestamp2)
format_time2 = date2.strftime('%Y-%m-%d %H:%S:%M')
print('format_time2: ', format_time2)
format_time1: 2021-04-05 21:03:28
format_time2: 2021-04-05 21:03:28
1.3 格式化时间字符串转时间戳
# 将格式化时间字符串转为元组(struct_time)
struct_time1 = time.strptime(format_time1, '%Y-%m-%d %H:%S:%M')
# 将元组(struct_time)转换为时间戳
timestamp1 = time.mktime(struct_time1)
print('timestamp1: ', timestamp1)
# 将格式化时间字符串转换为datetime实例
datetime_obj = datetime.strptime(format_time2, '%Y-%m-%d %H:%S:%M')
# 将datetime实例转换为时间戳
timestamp2 = datetime_obj.timestamp()
print('timestamp2: ', timestamp2)
# 将datetime实例转换成元组(struct_time)
struct_time2 = datetime_obj.timetuple()
# 再将元组转换成时间戳
timestamp2 = time.mktime(struct_time2)
print('timestamp2: ', timestamp2)
timestamp1: 1617629283.0
timestamp2: 1617629283.0
timestamp2: 1617629283.0
2. 时间的运算
时间的运算主要用
from datetime import datetime, timedelta
format_str = '%Y-%m-%d %H:%S:%M'
now = datetime.now()
yesterday = (now + timedelta(days=-1)).strftime(format_str)
print('yesterday: ', yesterday)
last_week = (now + timedelta(weeks=-1)).strftime(format_str)
print('last week: ', last_week)
yesterday: 2021-04-05 08:44:05
last week: 2021-03-30 08:44:05
不过,timedelta最大只能对时间进行周week的运算,如果像计算月和年就有点麻烦了,这时候一个第三方模块能够解决问题
$ pip3 install python-dateutil
last_month = (now + relativedelta(months=-1)).strftime(format_str)
next_year = (now + relativedelta(years=1)).strftime(format_str)
print('last month: ', last_month)
print('next year: ', next_year)
last month: 2021-03-06 08:44:05
next year: 2022-04-06 08:44:05
写法一样和timedelta的,就是范围更广