日期格式转换
记录 datetime 标准库相关的日期格式转换方法
格式代码:https://docs.python.org/zh-cn/3/library/datetime.html#strftime-and-strptime-format-codes
1. strftime 日期 --> 字符串
strftime: 根据给定的格式将对象转换为字符串
python
>>> datetime.datetime.now()
datetime.datetime(2022, 5, 12, 20, 12, 19, 226119)
>>>
>>> datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2022-05-12 20:12:29'
>>>2. strptime 字符串 --> 日期
strptime: 将字符串解析为给定相应格式的 datetime 对象
python
>>> datetime.datetime.strptime('2022-05-12 20:12:29', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2022, 5, 12, 20, 12, 29)
>>>3. timestamp 日期 --> 时间戳
python
>>> datetime.datetime.now().timestamp()
1652358360.562188
>>>3. fromtimestamp 时间戳 --> 日期
python
>>> ts = time.time()
>>> ts
1652357956.0824502
>>> datetime.datetime.fromtimestamp(ts)
datetime.datetime(2022, 5, 12, 20, 19, 16, 82450)
>>>4. timedelta 时间加减
python
>>> now + datetime.timedelta(days=7)
datetime.datetime(2022, 5, 19, 20, 36, 54, 922657)
# class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)从 timedelta 函数定义来看,没有 years,不能直接计算几年之后的日期
5. 更改时区
python
from datetime import datetime, timezone
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)6. 单独获取年月日时分秒
python
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2022, 5, 12, 20, 36, 54, 922657)
>>> now.year
2022
>>> now.month
5
>>> now.day
12
>>> now.hour
20
>>> now.minute
36
>>> now.second
54
>>> now.microsecond
922657
>>>