python - 如何正确格式化时间戳
问题描述
我有以下数据库中的时间戳信息:
time_format: str = "%d/%b/%Y %H:%M %Z"
timestamp = '2020-11-03T21:32:19.722012+00:00'
timezone = 'America/New_York'
如何使用 datetime 将此信息格式化为如下所示:
11/03/2020 17:32EST
我能够做到这一点:
datetime.datetime.now().fromisoformat(timestamp_utc).strftime(time_format)
但无法弄清楚如何用任何时间替换 datetime.now() 然后显示所需的时区代替“UTC”
解决方案
由于 python 没有开箱即用的出色时区支持,因此我建议将此pytz
库用于此用例。
from datetime import datetime
import pytz
# Input
datetime_str = '2020-11-03T21:32:19.722012+00:00'
timezone_str = 'America/New_York'
output_format = '%m/%d/%Y %H:%M %Z'
# Convert input datetime str to python datetime obj
# this datetime is timezone aware, with tz=UTC
utc_datetime = datetime.fromisoformat(datetime_str)
# Convert input timezone str to a pytz timezone object
new_timezone = pytz.timezone(timezone_str)
# Adjust the UTC datetime to use the new timezone
new_timezone_datetime = utc_datetime.astimezone(new_timezone)
# Print in the desired output format
print(new_timezone_datetime.strftime(output_format))
如果我运行上面的代码,我会得到以下...
11/03/2020 16:32 EST
编辑:它16:32
代替的原因17:32
是因为American/New_York
与 相同US/Eastern
,因为它们在一年中的不同时间点使用EST
/ EDT
(夏令时)。2020-11-03
碰巧掉进去了EST
。
推荐阅读
- html - 如何将参数作为本地存储中的变量添加到 URL 路径?
- css - 如何正确导入 googlefonts?
- javascript - npm install electron 错误 - 无法验证第一个证书
- vue.js - 在 Bootstrap Vue 中动态创建模板槽
- hdf5 - 在 .net 中读取 HDF5 文件
- java - 使用 LinkedHashMap 的字符串中的第一个唯一字符
- sql - Django条件多对一关系?
- javascript - Vanilla JavaScript Flip Card 游戏不工作
- c++ - C++ 类作为列表长度说明符?
- python - 从 Flask 调用任意 Python 函数的更优雅的方式