【问题标题】:Converting time zone from utc to america/new_york on a dictionary using python使用 python 在字典上将时区从 utc 转换为 america/new_york
【发布时间】:2020-06-28 13:33:23
【问题描述】:

我有一个时间戳字典,它是我首先转换为日期时间对象的字符串。 我需要做相当于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'
 }

【问题讨论】:

  • 你能展示你的数据吗?
  • 您确定您使用的是pytz.timezone 而不是datetime.timezone 吗?

标签: python dictionary pytz


【解决方案1】:

在不了解所有背景的情况下...

from datetime import datetime, timedelta
from pytz import timezone
import pytz

dataj = {'$insert_id': '14ae91db-4b9e-4898-88dd-62fc9f99dcb4','$schema': 12, 'adid': None,'event_time': '2019-12-01 00:00:19.251000'}

print(dataj)

for schema, value in dataj.items():
    if schema == 'event_time':
        correct_time = datetime.strptime(dataj["event_time"].split('.')[0], "%Y-%m-%d %H:%M:%S")
        dataj['event_time'] = correct_time.replace(tzinfo=timezone('America/New_York'))

print(dataj)

【讨论】:

    【解决方案2】:

    这个answer 展示了如何将所需的时区添加到日期时间对象。您需要使用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>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 1970-01-01
      • 2012-04-09
      相关资源
      最近更新 更多