python之time和datetime模块

  • 时间:
  • 浏览:5

datetime.datetime.timedelta用于计算有有有两个多日期之间的差值:

print(datetime.datetime.now())>>>2018-10-18 19:15:17.691425

time类有两个参数,datetime.time(hour,minute,second,microsecond,tzoninfo)

print(datetime.time(8,5,32))print(datetime.time(8,5,32,32))>>>08:05:32>>>08:05:32.000032

image.png

datetime模块定义了两个类,分别是

cls.strftime("时间格式")

指定时间格式

a= datetime.time(8,5,32,32)print(a.strftime("%H:%M"))>>>08:05

print(time.time())>>>1539847769.6119404

print(datetime.date.fromtimestamp(1539847769))>>>2018-10-18

a = datetime.date.today()print(a.replace(year=2010))>>>2010-10-18

print(datetime.date(2017,12,1))>>>2017-12-01

datetime.time.utcoffset()

返回时区的时间偏移量:略

print(time.gmtime(time.time()))>>>time.struct_time(tm_year=2018, tm_mon=10, tm_mday=18, tm_hour=8, tm_min=10, tm_sec=16, tm_wday=3, tm_yday=291, tm_isdst=0)

image.png

a = datetime.date.today()print(a.timetuple())>>>time.struct_time(tm_year=2018, tm_mon=10, tm_mday=18, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=291, tm_isdst=-1)

datetime.time.tzname()

返回时区名字:略

print(time.localtime())>>>time.struct_time(tm_year=2018, tm_mon=10, tm_mday=18, tm_hour=15, tm_min=35, tm_sec=0, tm_wday=3, tm_yday=291, tm_isdst=0)

print(datetime.datetime.now().date())>>>2018-10-18

a = datetime.date.today()print(datetime.date.isoweekday(a))>>>4

print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))>>>2018-10-18 19:21:13

print(datetime.date.today())>>>2018-10-18

a = datetime.datetime.strptime("2018-10-18 19:21:37",'%Y-%m-%d %H:%M:%S')print(a,type(a))>>>2018-10-18 19:21:37 <class 'datetime.datetime'>

image.png

print(time.strptime("2018-10-18 15:56:42","%Y-%m-%d %H:%M:%S"))>>>time.struct_time(tm_year=2018, tm_mon=10, tm_mday=18, tm_hour=15, tm_min=56, tm_sec=42, tm_wday=3, tm_yday=291, tm_isdst=-1)

print(time.time())1539849828.0901003

a = datetime.date.today()print(datetime.date.weekday(a))>>>3

print(datetime.datetime.now().time())>>>19:16:54.497104

print(time.mktime(time.localtime()))>>>1539849828.0 注意和time.time()的区别:

附一:

醉里挑灯看剑,梦回吹角连营。八百里分麾下炙,五十弦翻塞外声。沙场秋点兵。

马作的卢太快了 了 ,弓如霹雳弦惊。了却君王天下事,赢得生前肩头名。可怜白所处!

附二:time时间之间的转换

print(time.strftime("%Y-%m-%d %H:%M:%S"))>>>2018-10-18 15:56:42

cls.replace()

替换时节 秒

a= datetime.time(8,5,32,32)print(a.replace(hour=18))>>>18:05:32.000032

datetime模块类的使用大同小异,有一些一些法律妙招大伙儿儿儿肯能这辈子都用不上,datetime类的法律妙招比较多,在这里让我捡重点的列一下: