首页投稿(暂停使用,暂停投稿)

python---关于时间的处理(二)

2017-07-20  本文已影响0人  小蜗牛的成长

继续上一篇关于时间处理的总结

  上一篇主要讲述time模块,今天主要讲datetime模块,相比time模块,功能更为强大、更为优雅简洁。

datetime包括以下几个类:

接下来分别讲解

date类

d=date.today()
d1=date(2017, 07, 06)
print("当前日期:{},自定义日期:{}".format(d,d1))
print("当前日期:{}对应的星期:{}".format(d,d.isoweekday()))
print("将date对象:{}转化成其他格式:{}".format(d,d.strftime("%Y/%m/%d")))
print("将日期:{}的day替换,替换后:{}".format(d,d.replace(day=23)))
print("日期:{} 与另外一个日期:{}的差值:{}".format(d,d1,(d-d1).days))
#结果
当前日期:2017-07-20,自定义日期:2017-07-06
当前日期:2017-07-20对应的星期:4
将date对象:2017-07-20转化成其他格式:2017/07/20
将日期:2017-07-20的day替换,替换后:2017-07-23
日期:2017-07-20 与另外一个日期:2017-07-06的差值:14

time类

t=time(11,12,12)
print("自定义time对象:{}".format(t))
print("使用默认的格式,格式化time对象:{}".format(t.isoformat()))
#结果
自定义time对象:11:12:12
使用默认的格式,格式化time对象:11:12:12

datetime类
  datetime类继承date,包括date与time的所有信息。它的构造函数如下:
datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ),各参数的含义与date、time的构造函数中的一样,参数值的范围同date、time

from datetime import *
ptimestamp=1400000000
datestring="2017/11/22 12:22"
now=datetime.now()
utcnow=datetime.utcnow()
date=datetime.date(now)
time=datetime.time(now)
localdatetime=datetime.fromtimestamp(ptimestamp)
utcdatetime=datetime.utcfromtimestamp(ptimestamp)
newformat=datetime.strptime(datestring,"%Y/%m/%d %H:%M")
print("当前时间----本地时区当前时间:{},0时区当前时间:{}".format(now,utcnow))
print("指定datetime对象的日期:{},时间:{}".format(date,time))
print("指定时间戳:{}转化成本地时区对应的datetime对象:{},转化成0时区对应的datetime对象:{}".format(ptimestamp,localdatetime,utcdatetime))
print("指定格式的时间字符串转化成datetime对象:原来:{},现在:{}".format(datestring,newformat))
endtime=datetime.now()
print("2个datetime对象的毫秒时间差:{}".format((endtime-now).microseconds))
print("当前时间:{}基础上计算50天之后的日期时间:{}".format(datetime.now(),datetime.now() + timedelta(days =50)))
#结果
当前时间----本地时区当前时间:2017-07-20 14:47:09.605000,0时区当前时间:2017-07-20 06:47:09.605000
指定datetime对象的日期:2017-07-20,时间:14:47:09.605000
指定时间戳:1400000000转化成本地时区对应的datetime对象:2014-05-14 00:53:20,转化成0时区对应的datetime对象:2014-05-13 16:53:20
指定格式的时间字符串转化成datetime对象:原来:2017/11/22 12:22,现在:2017-11-22 12:22:00
2个datetime对象的时间差:5000
当前时间:2017-07-20 14:47:09.610000基础上计算50天之后的日期时间:2017-09-08 14:47:09.610000

  时区的转化参见 pytz模块,这里不展开深入了解

上一篇 下一篇

猜你喜欢

热点阅读