python日期时间库

img

time 模块

本地时间和utc时间

time.localtime time.gtime[secs] 会返回一个struct_time 时间元组,属性为只读,可以通过索引取值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
In [10]: time.localtime()
Out[10]: time.struct_time(tm_year=2023, tm_mon=2, tm_mday=25, tm_hour=17, tm_min=9, tm_sec=42, tm_wday=5, tm_yday=56, tm_isdst=0)


In [11]: t = time.localtime()
In [13]: t[0] = 2010
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[13], line 1
----> 1 t[0] = 2010

TypeError: 'time.struct_time' object does not support item assignment

In [14]: t[1]
Out[14]: 2

time.mktime([struct_time]) 转换为时间戳

1
2
In [17]: time.mktime(time.localtime())
Out[17]: 1677317212.0

时间格式化

strftime(format,[struct_time]) 可以进行时间格式化,没指定时间元组默认是本地时间

1
2
In [16]: time.strftime('%Y-%m-%d %H:%M:%S')
Out[16]: '2023-02-25 17:16:20'

用到的格式有如下

%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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
In [18]: time.strptime?
Docstring:
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()).


In [19]: strtime = '2023-02-25 17:16:20'

In [20]: time.strptime(strtime,"%Y-%m-%d %H:%M:%S")
Out[20]: time.struct_time(tm_year=2023, tm_mon=2, tm_mday=25, tm_hour=17, tm_min=16, tm_sec=20, tm_wday=5, tm_yday=56, tm_isdst=-1)

image-20230225170445545

datetime 模块

https://www.cnblogs.com/tkqasn/p/6001134.html

https://www.liujiangblog.com/course/python/69

https://opensource.com/article/17/5/understanding-datetime-python-primer

https://zhuanlan.zhihu.com/p/37164491


python日期时间库
https://kingjem.github.io/2024/10/14/日期时间库/
作者
Ruhai
发布于
2024年10月14日
许可协议