time模块常用方法

time.time()

生成一个float类型的时间戳
在这里插入图片描述

time.localtime()

  • 返回当前的时间类型为struct_time类型的时间
import time
t1 = time.localtime()

print(t1, type(t1))

#time.struct_time(tm_year=2020, tm_mon=1, tm_mday=23, tm_hour=16, tm_min=51, tm_sec=15, tm_wday=3, tm_yday=23, tm_isdst=0) <class 'time.struct_time'>
  • 可以接受一个为整数的时间戳类型的时间
import time
t1 = time.localtime(int(time.time()))
print(t1, type(t1))
#time.struct_time(tm_year=2020, tm_mon=1, tm_mday=23, tm_hour=16, tm_min=54, tm_sec=39, tm_wday=3, tm_yday=23, tm_isdst=0) <class 'time.struct_time'>

time.asctime()

  • 返回当前时间的这种格式的字符串
    在这里插入图片描述

time.strftime()

  • 传入格式struct_time,返回按照format格式格式化后的时间字符串
t5 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(t5, type(t5))

在这里插入图片描述
格式占位符参考

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.

time.strptime()

  • 将字符串时间转化为struct_time,time.strftime()的一个逆向操作
    在这里插入图片描述
发布了23 篇原创文章 · 获赞 0 · 访问量 350

猜你喜欢

转载自blog.csdn.net/Aerkui/article/details/104076640