简体   繁体   English

当地时间到 UTC

[英]Local time to UTC

'v' is a python datetime object read from a DB - '2020-09-24 00:00:00' 'v' 是从数据库读取的 python 日期时间 object - '2020-09-24 00:00:00'

I would like to stored above in LDAP in Zulu - so '2020-09-24 07:00:00' - as I am located in Los Angeles.我想存储在祖鲁语的 LDAP 中——所以“2020-09-24 07:00:00”——因为我位于洛杉矶。

v = v.strftime('%Y%m%d%H%M%SZ') - converts directly to 20200924000000Z (not 20200924070000Z). v = v.strftime('%Y%m%d%H%M%SZ') - 直接转换为 20200924000000Z(不是 20200924070000Z)。

Is that the correct behaviour?这是正确的行为吗? If not, how can I best covert time read, to UTC, prior to injecting to LDAP?如果没有,在注入 LDAP 之前,我如何最好地隐蔽时间读取 UTC?

'v' is a python datetime object read from a DB - '2020-09-24 00:00:00' 'v' 是从数据库读取的 python datetime 对象 - '2020-09-24 00:00:00'

I would like to stored above in LDAP in Zulu - so '2020-09-24 07:00:00' - as I am located in Los Angeles.我想存储在祖鲁语的 LDAP 上面 - 所以'2020-09-24 07:00:00' - 因为我位于洛杉矶。

v = v.strftime('%Y%m%d%H%M%SZ') - converts directly to 20200924000000Z (not 20200924070000Z). v = v.strftime('%Y%m%d%H%M%SZ') - 直接转换为 20200924000000Z(不是 20200924070000Z)。

Is that the correct behaviour?这是正确的行为吗? If not, how can I best covert time read, to UTC, prior to injecting to LDAP?如果没有,在注入 LDAP 之前,如何最好地将时间读取到 UT​​C?

  • parse the string to a datetime object (which will be naive; unaware of the time zone) - your format allows to use fromisoformat , which is more efficient than strptime将字符串解析为日期时间 object(这将是幼稚的;不知道时区)——您的格式允许使用fromisoformat ,这比strptime有效
  • set the appropriate time zone (here: US/Pacific for LA)设置适当的时区(这里:洛杉矶的美国/太平洋)
  • change time zone to UTC将时区更改为 UTC
  • output as string in desired format output 作为所需格式的字符串

Since pytz will be deprecated with the release of Python 3.9, I suggest using dateutil .由于 pytz 将随着 Python 3.9 的发布而被弃用,我建议使用dateutil With Python 3.9, you'll have zoneinfo for these kind of things.使用Python 3.9,您将拥有用于此类操作的区域信息。

from datetime import datetime
from dateutil.tz import gettz

s = '2020-09-24 00:00:00'
dt = datetime.fromisoformat(s)

# set time zone
dt = dt.replace(tzinfo=gettz('US/Pacific'))

# to UTC
dt = dt.astimezone(gettz('UTC'))

# to string
out = dt.strftime('%Y%m%d%H%M%SZ')
# '20200924070000Z'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM