1:datetime函数
1):获取当前时间
import datetime #获取当前时间 <class 'datetime.datetime'> 2020-03-08 22:14:11.505886 print(datetime.datetime.now()) #把<class 'datetime.datetime'>转成<class 'str'> 2020-03-08 22:14:11 print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) #把<class 'str'>转成<class 'datetime.datetime'> 2020-03-08 22:10:15 print(datetime.datetime.strptime('2020-03-08 22:10:15','%Y-%m-%d %H:%M:%S'))
#获取今年第几周 <class 'str'> 09 print(var_nowday.strftime('%W'))
%y 两位数的年份表示(00-99) %Y 四位数的年份表示(000-9999) %m 月份(01-12) %d 月内中的一天(0-31) %H 24小时制小时数(0-23) %I 12小时制小时数(01-12) %M 分钟数(00=59) %S 秒(00-59)
%W 返回当周是当年的第几周 以周一为第一天 %w 当天在当周的天数,范围为[0, 6],6表示星期天
2):当前周,日,月,年
import datetime var_nowday = datetime.datetime.now() #获取当前年份 20 2020 print(var_nowday.strftime('%y'),var_nowday.strftime('%Y')) #获取当前月份 03 print(var_nowday.strftime('%m')) #获取当前天 08 print(var_nowday.strftime('%d')) #获取当前周 6+1 print(var_nowday.weekday())
3):与时间戳相互转换
import datetime
var_nowday = datetime.datetime.now()
#把当前时间转换成时间戳<class 'float'> 1583677775.952189
print(datetime.datetime.timestamp(var_nowday))
#把时间戳转换成datetime类型 2020-03-08 22:29:35
print(datetime.datetime.fromtimestamp(1583677775))
4):日期加减操作
import datetime var_nowday = datetime.datetime.now() #当前时间 2020-03-08 22:41:15.456298 print(var_nowday) #当前时间加1秒,减1秒,返回<class 'datetime.datetime'> #2020-03-08 22:41:16.456298 print(var_nowday+datetime.timedelta(seconds=1)) #2020-03-08 22:41:14.456298 print(var_nowday+datetime.timedelta(seconds=-1)) #当前时间加1分钟 2020-03-08 22:42:15.456298 print(var_nowday+datetime.timedelta(minutes=1)) #当前时间加1小时 2020-03-08 23:41:15.456298 print(var_nowday+datetime.timedelta(hours=1)) #当前时间加1天 2020-03-09 22:41:15.456298 print(var_nowday+datetime.timedelta(days=1)) #当前时间加1周 2020-03-15 22:41:15.456298 print(var_nowday+datetime.timedelta(weeks=1))
来源:oschina
链接:https://my.oschina.net/u/3452443/blog/3190259