python中时间处理小结

python中时间处理

总结一下python中的常用时间处理相关的模块的使用. 主要是 time datetime 两个模块.

time

比较底层的时间处理相关模块. 记录常用的时间操作方法

  1. time.time()
    获取当前时间戳(单位是, 和一般的JAVA默认毫秒时间戳单位不同)
time.time()
1611794576.614294
  1. time.localtime([seconds])
    将时间戳转换为time.struct_time 类型本地时间, 如果不给定参数, 使用当前时间的时间戳.
localtime(...)
    localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                              tm_sec,tm_wday,tm_yday,tm_isdst)
    
    Convert seconds since the Epoch to a time tuple expressing local time.
    When 'seconds' is not passed in, convert the current time instead.

struct_time 可以看成同一时间戳不同时区的不同表达, 这个值会因为时区不同而不同.

  1. time.strftime()
strftime(format[, tuple]) -> string
    
    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used.

格式化时间, 注意此处的第二个参数是tuple, 实际使用的时候传递的是struct_time. 如果第二个参数不赋值, 那么以time.localtime() 作为默认值, 即是以某种格式, 格式化本地时间

比如格式化当前时间

time.strftime('%Y-%m-%d %H:%M:%S')
'2021-01-28 08:57:20'
  1. time.strptime
    将一个时间的字符串形式转换成时间元祖 time.struct_time
strptime(string, format) -> struct_time
    
    Parse a string to a time tuple according to a format specification.
    See the library reference manual for formatting codes (same as
    strftime()).
time.strptime('2020-02-03', '%Y-%m-%d')
time.struct_time(tm_year=2020, tm_mon=2, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=34, tm_isdst=-1)
  1. time.mktime

将时间元祖(time.struct_time)转换为时间戳, 和 time.localtime() 相反

mktime(tuple) -> floating point number
    
    Convert a time tuple in local time to seconds since the Epoch.
    Note that mktime(gmtime(0)) will not generally return zero for most
    time zones; instead the returned value will either be equal to that
    of the timezone or altzone attributes on the time module.
time.mktime(time.localtime())
1611796088.0
  1. time.sleep(seconds)
sleep(seconds)
    
    Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.

线程休眠时间

time模块里面的时间操作比较底层, 涉及到一个结构time.struct_time 时间元祖. 格式化以及反向操作, 都是以时间元祖(time.struct_time) 为基础进行的. 总体完成在时间格式化字符串, 时间戳以及时间元祖之间的转换操作. 如下的转换关系:

时间格式字符串 <--strptime/strftime--> struct_time(结构化时间表达, 跟时区有关) <--localtime/mktime--> timestamp(时间戳, 单位秒)

常用功能 time.sleep([sec]) 线程休眠
以及计算程序执行时间

start_time = time.now()
......
duration = time.now() - start_time

datetime

datetime 是一个模块, 相比于time模块具有更多高级的功能相比于time中只有struct_time这种结构化时间类型. datetime 模块中有更多的表示时间的类,其中有4类比较重要, 一个是同名的datetime 一个是 timedelta, 一个是 time, 一个是date. 实际在使用import 的时候 因为 datetime类和模块同名了, 所以其实最好是 import datetime 而不是 from datetime import datetime 这种导入, 前者可操作的类型更多一些.

datetime.date: 只需要传递年月日, 表征的是日期

date(year, month, day) --> date object
datetime.date(2020,2,1)
datetime.date(2020, 2, 1)

datetime.time: 只需要传递时分秒毫秒时区信息, 表征的是24小时时间.

time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object
datetime.time(18,2,2)
datetime.time(18, 2, 2)

datetime.datetime: 上面两者的结合, 表征日期和时间

datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])
 |  
 |  The year, month and day arguments are required. tzinfo may be None, or an
 |  instance of a tzinfo subclass. The remaining arguments may be ints.
datetime.datetime(2020,2,2,20,18,11)
datetime.datetime(2020, 2, 2, 20, 18, 11)

datetime.timedelta: 时间间隔对象, 天,时,分,秒,毫秒,微秒的差值对象. 可根据当前时间和给定日期时间差值计算新的日期时间.

Difference between two datetime values.
 |  
 |  timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
 |  

a = datetime.datetime.now()
print(a)
print(a + datetime.timedelta(days=1))
2021-01-28 09:51:00.202448
2021-01-29 09:51:00.202448

主要操作:

  1. 时间日期类型格式化 以及 字符串转换成时间.

从时间日期类型到字符串 三个类型都有 strftime这个函数

datetime.date.today().strftime('%Y-%m-%d')
datetime.time(8,20,20).strftime('%H:%m:%S')
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-28'
'08:01:20'
'2021-01-28 10:06:06'

反过来从字符串到日期时间对象, 只有 datetime.strptime 可以实现, 其他类型 date 和 time 没有这个函数

datetime.datetime.strptime('2020-02-28 10:06:08', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2020, 2, 28, 10, 6, 8)
  1. 日期时间对象到时间戳

datetime 有 timestamp函数 直接转换到时间戳

datetime.datetime.now().timestamp()
1611799911.872106

date: 没有这个函数 只能通过timetuple 函数转换成time.struct_time 再通过time.mktime() 实现转换成时间戳.

t = datetime.date(2021,1,28)
time.mktime(t.timetuple())
1611763200.0

但是从字符串到时间 date和 datetime 都提供了 fromtimestamp 方法完成时间戳到日期时间类型转换.

datetime.datetime.fromtimestamp(datetime.datetime.now().timestamp())
datetime.date.fromtimestamp(datetime.datetime.now().timestamp())
datetime.datetime(2021, 1, 28, 10, 17, 0, 298880)
datetime.date(2021, 1, 28)

总之: datetime模块包含了较多的时间日期的结构化类型, 在time模块上提供了更简洁强大的api完成时间日期的操作.

小结

需要较低层较简单的时间操作(比如计算程序运行时间)time模块就够了, 但是如果要更高级的日期操作, 需要使用datetime模块.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章