简体   繁体   中英

Local time to UTC

'v' is a python datetime object read from a DB - '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.

v = v.strftime('%Y%m%d%H%M%SZ') - converts directly to 20200924000000Z (not 20200924070000Z).

Is that the correct behaviour? If not, how can I best covert time read, to UTC, prior to injecting to LDAP?

'v' is a python datetime object read from a DB - '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.

v = v.strftime('%Y%m%d%H%M%SZ') - converts directly to 20200924000000Z (not 20200924070000Z).

Is that the correct behaviour? If not, how can I best covert time read, to UTC, prior to injecting to LDAP?

  • 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
  • set the appropriate time zone (here: US/Pacific for LA)
  • change time zone to UTC
  • output as string in desired format

Since pytz will be deprecated with the release of Python 3.9, I suggest using dateutil . With Python 3.9, you'll have zoneinfo for these kind of things.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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