python日期相关操作
当前日期时间
import datetime result=datetime.datetime.now() print(result) # 2018-05-08 16:53:30.101000
格式化时间
1. datetime => string
now = datetime.datetime.now() now.strftime('%Y-%m-%d %H:%M:%S') #输出2012-03-05 16:26:23.870105
strftime是datetime类的实例方法。
2. string => datetime
t_str = '2012-03-05 16:26:23' d = datetime.datetime.strptime(t_str, '%Y-%m-%d %H:%M:%S')
时间加减和间隔(日、周、时、分、秒、毫秒、微秒)
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[,hours[, weeks]]]]]]])
加一天
import datetime result=(datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S") print(result) # 2018-05-09 16:56:07
减一天
import datetime result=(datetime.datetime.now()+datetime.timedelta(days=-1)).strftime("%Y-%m-%d %H:%M:%S") print(result) # 2018-05-07 16:56:07
间隔
d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S') d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S') delta = d1 - d2 print(delta.days)
时间加减(年、月)
relativedelta([years[,months]])
减去一年
import datetime from dateutil.relativedelta import relativedelta d = datetime.datetime.strptime('20180131', '%Y%m%d') print(d) // 2018-01-31 00:00:00 print((d - relativedelta(years=1)).strftime('%Y%m%d')) // 20170131
时区转换
from datetime import datetime from datetime import timezone from datetime import timedelta # 世界标准时间 utc_time = datetime(2019, 7, 30, 7, 50, 0) # 北京时间UTC+8 cst_time =utc_time.astimezone(timezone(timedelta(hours=-8))).strftime("%Y-%m-%d %H:%M:%S")