python - 使用 python 在字典上将时区从 utc 转换为 america/new_york
问题描述
我有一个时间戳字典,它是我首先转换为日期时间对象的字符串。我需要做相当于timestamp at time zone 'UTC' at time zone 'America/New_York'
这里的 sql 我有一个 for 循环
for x in dataj:
x['event_time'] = datetime.strptime(x['event_time'].split('.')[0], "%Y-%m-%d %H:%M:%S")
x['event_time'] = x['event_time'].replace(tzinfo=timezone('America/New_York'))
我收到这个错误
TypeError: timezone() argument 1 must be datetime.timedelta, not str
dataj 看起来像这样:
P(dataj[0])
{'$insert_id': '14ae91db-4b9e-4898-88dd-62fc9f99dcb4',
'$schema': 12,
'adid': None,
'event_time': '2019-12-01 00:00:19.251000'
}
解决方案
此答案显示了如何将所需的时区添加到 datetime 对象。你需要使用pytz
.
这是与您的帖子相似的部分。
import datetime
import pytz
x = '2019-12-01 00:00:19.251000'
as_datetime = datetime.datetime.strptime(x.split('.')[0], "%Y-%m-%d %H:%M:%S")
as_datetime # datetime.datetime(2019, 12, 1, 0, 0, 19)
utcmoment = as_datetime.replace(tzinfo=pytz.utc)
as_nytz = utcmoment.astimezone(pytz.timezone('America/New_York'))
as_nytz # datetime.datetime(2019, 11, 30, 19, 0, 19, tzinfo=<DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)
推荐阅读
- asp.net - 在 ASP.NET Core razor 页面中跨帖子和重定向保留现有查询字符串的最简单方法是什么?
- linkedin - UGC 视频发布到用户个人资料
- android - Flutter - 使用 Column/Expanded/ListView 的布局问题
- c++ - 如何使用 cxx crate 调用 C++ 构造函数?
- prisma - Prisma 客户端查询最新
- vb.net - 使用 vb.net 编辑
- angular - Angular 10 中的 @Input 与依赖注入
- angular - 使用服务的角度多个可观察请求
- excel - 如何有效控制多个嵌套循环而不会出现 RT 错误?
- discord.py - discord.py 通过命令发送消息,该命令在设定的时间后计算有多少人“投票”了反应(自定义表情符号)