0

'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?

user353829
  • 1,244
  • 5
  • 25
  • 38

1 Answers1

1
  • 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'
FObersteiner
  • 22,500
  • 8
  • 42
  • 72