Python time模块/datetime模块

嘉美伯爵

Python datetime模块 time模块 224

注意

time模块直接和操作系统打交道,而datetime中的datetime、time、date三个模块均是自定义的结构时间类,其功能实现 全部依赖于time

time

  • time.time()
# 获取时间戳
In [35]: time.time()
Out[35]: 1584063173.6769917
  • time.ctime()
# 获取美国格式时间
In [42]: time.ctime()
Out[42]: 'Fri Mar 13 09:38:35 2020'
  • time.gmtime()
# 美国时间
In [64]: time.gmtime()
Out[64]: time.struct_time(tm_year=2020, tm_mon=3, tm_mday=13, tm_hour=1, tm_min=53, tm_sec=12, tm_wday=4, tm_yday=73, tm_isdst=0)
  • time.localtime
# 结构化时间,本地时间
In [46]: time.localtime()
Out[46]: time.struct_time(tm_year=2020, tm_mon=3, tm_mday=13, tm_hour=9, tm_min=40, tm_sec=14, tm_wday=4, tm_yday=73, tm_isdst=0)
  • time.mktime
In [53]: time.mktime( datetime.now().timetuple())
Out[53]: 1584063841.0

datetime

datetime

  • fromisoformat
# iso标准时间
In [73]: datetime.fromisoformat('2020-12-12 12:12:12')
Out[73]: datetime.datetime(2020, 12, 12, 12, 12, 12)
  • now
# 今天时间
In [75]: datetime.now()
Out[75]: datetime.datetime(2020, 3, 13, 10, 10, 49, 902963)
  • timestmap
# 时间戳
In [79]: datetime.now().timestamp()
Out[79]: 1584065559.701251
  • fromstmap
In [85]: datetime.fromtimestamp(1607746332.0)
Out[85]: datetime.datetime(2020, 12, 12, 12, 12, 12)
  • iscalendar
# 年 第几周 周几
In [91]: datetime.now().isocalendar()
Out[91]: (2020, 11, 5)

date

  • today
# 返回今天
In [99]: date.today()
Out[99]: datetime.date(2020, 3, 13)
  • isoweekday
# 返回周几
In [110]: date.isoweekday(date.today())
Out[110]: 5
  • strftime
# 没有strptime 只能这样用
In [116]: date.today().strftime('%Y-%m-%d')
Out[116]: '2020-03-13'
  • replace
In [121]: date.today().replace(day=12)
Out[121]: datetime.date(2020, 3, 12)

time

该模块没有构造方法,只能手动构造,用法和date一致

timedelta

  • 日期加减
In [96]: datetime.now() + timedelta(days=1)
Out[96]: datetime.datetime(2020, 3, 14, 10, 19, 59, 795352)

日期格式化

  • strftime(datetime->str)

格式化时间,格式化在前

In [62]: time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
Out[62]: '2020-03-13 09:52:08'
  • strptime(str->datetime)

输出时间,格式化在后

In [68]: time.strptime('2020-12-12 12:12:12', '%Y-%m-%d %H:%M:%S')
Out[68]: time.struct_time(tm_year=2020, tm_mon=12, tm_mday=12, tm_hour=12, tm_min=12, tm_sec=12, tm_wday=5, tm_yday=347, tm_isdst=-1)

时间戳互转

  • 时间戳转日期
In [55]: datetime.fromtimestamp(time.time())
Out[55]: datetime.datetime(2020, 3, 13, 9, 45, 21, 386144)
  • 日期转时间戳
# time转
In [53]: time.mktime(datetime.now().timetuple())
Out[53]: 1584063841.0
# datetime转
In [79]: datetime.now().timestamp()
Out[79]: 1584065559.701251
# 综合转
In [83]: datetime.strptime('2020-12-12 12:12:12', '%Y-%m-%d %H:%M:%S').timestamp()
Out[83]: 1607746332.0

最大时间

  • date/time/datetime
    # time
    In [106]: time.max
    Out[106]: datetime.time(23, 59, 59, 999999)
    # datetime
    In [104]: datetime.max
    Out[104]: datetime.datetime(9999, 12, 31, 23, 59, 59, 999999)
    # date
    In [102]: date.max
    Out[102]: datetime.date(9999, 12, 31)

属性

在生成对应的时间类后,注意使用year、month等属性,不用截取

参考文档