首页 > 解决方案 > 使用 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'
 }

标签: pythondictionarypytz

解决方案


答案显示了如何将所需的时区添加到 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>)

推荐阅读