04-日期格式转换

  • 阅读: 251
  • 更新: 2022-06-11

记录 datetime 标准库相关的日期格式转换方法
格式代码:https://docs.python.org/zh-cn/3/library/datetime.html#strftime-and-strptime-format-codes

1. strftime 日期 --> 字符串

strftime: 根据给定的格式将对象转换为字符串

1
2
3
4
5
6
>>> 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 对象

1
2
3
>>> 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 日期 --> 时间戳

1
2
3
>>> datetime.datetime.now().timestamp()
1652358360.562188
>>>

3. fromtimestamp 时间戳 --> 日期

1
2
3
4
5
6
>>> ts = time.time()
>>> ts
1652357956.0824502
>>> datetime.datetime.fromtimestamp(ts)
datetime.datetime(2022, 5, 12, 20, 19, 16, 82450)
>>>

4. timedelta 时间加减

1
2
3
>>> 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. 单独获取年月日时分秒

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
>>> 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
>>>

=== 全文完 ===


欢迎加入QQ群:778391413

京公网安备 11011302003970号 京ICP备2022012301号-1