time和datetime

  time和datetime都是时间模块。

  时间格式分成三种:

  1.时间戳格式,也就是从1970年1月1日起的秒数,通常用于时间计算

  2.格式化时间格式,将时间分成9个部分,方便取时间的任何字段,比如年,月,日,时,分,秒,星期,全年的第几天,是否是夏令时,time.localtime()

  3.字符串时间,通过自定义的时间格式,将时间格式化为想要的时间格式

 

  三种时间格式之间的相互转换

  时间戳---->格式化时间,time.localtime()

  格式化时间---->时间戳,time.mktime()

  字符串时间---->时间戳,time.strptime()

  时间戳---->字符串时间,time.strftime()

 

  datetime也是一种时间格式,其中datetime.datetime.now()直接取当前时间,但是datetime.timedela,可以直接进行时间计算,比如之后的几天是什么时间,前面的几年是什么时间。

  datetime和时间戳之间可以进行转化,datetime.datetime.fromtimestamp()

import time
import datetime

time_string = '1980-12-05 12:18:32'
# 把字符串的时间格式,转换为结构化的时间格式
time_struc = time.strptime(time_string,'%Y-%m-%d %H:%M:%S')
# 将结构化的时间,转化为时间戳的格式,才能参与计算
time_stamp = time.mktime(time_struc)
print(time_stamp)
# 时间戳格式的时间,计算之后,再转换为字符串的时间
new_time_stamp = time_stamp + 7*24*60*60
new_time_struc = time.localtime(new_time_stamp)
new_time_string = time.strftime('%Y-%m-%d %H:%M:%S',new_time_struc)
print(new_time_string)

time_datetime = datetime.datetime.fromtimestamp(time_stamp)
new_time_datetime = datetime.datetime.fromtimestamp(new_time_stamp)
print(new_time_datetime)

  

posted @ 2020-10-18 09:51  波波波波波  阅读(509)  评论(0编辑  收藏  举报