1

I have the following string format: date = 'Jun 8, 2021 PDT' I'm trying to convert that string into a datetime object. Right now I have it at:

dt_o = dt.strptime(date, '%b %d, %Y')

That gets me almost all the way there, but I am still getting the following error:

ValueError: unconverted data remains: PDT

Is there a way to include the 'PDT' in the original creation of the datetime object?. My other option is to strip the string of the 'PDT' and create a timezone unaware object.

dt_o = dt.strptime(date.rsplit(None, 1)[0], '%b %d, %Y') gives me an object of: datetime.datetime(2021, 6, 8, 0, 0).

is there a way I can apply the PDT timezone to that? I'd need to be able to convert it from the string date.rsplit(None, 1)[1], since it won't always be PDT

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
bmorgs
  • 195
  • 1
  • 12

2 Answers2

1

It is a common misconception that %Z can parse arbitrary abbreviated time zone names. It cannot. See especially the "Notes" section #6 under technical detail in the docs.

You'll have to do that "by hand" since many of those abbreviations are ambiguous. Here's an option how to deal with it using only the standard lib:

from datetime import datetime
from zoneinfo import ZoneInfo

# we need to define which abbreviation corresponds to which time zone
zoneMapping = {'PDT' : ZoneInfo('America/Los_Angeles'),
               'PST' : ZoneInfo('America/Los_Angeles'),
               'CET' : ZoneInfo('Europe/Berlin'),
               'CEST': ZoneInfo('Europe/Berlin')}

# some example inputs; last should fail
timestrings = ('Jun 8, 2021 PDT', 'Feb 8, 2021 PST', 'Feb 8, 2021 CET',
               'Aug 9, 2020 WTF')

for t in timestrings:
    # we can split off the time zone abbreviation
    s, z = t.rsplit(' ', 1)
    # parse the first part to datetime object
    # and set the time zone; use dict.get if it should be None if not found
    dt = datetime.strptime(s, "%b %d, %Y").replace(tzinfo=zoneMapping[z])
    print(t, "->", dt)

gives

Jun 8, 2021 PDT -> 2021-06-08 00:00:00-07:00
Feb 8, 2021 PST -> 2021-02-08 00:00:00-08:00
Feb 8, 2021 CET -> 2021-02-08 00:00:00+01:00

Traceback (most recent call last):

    dt = datetime.strptime(s, "%b %d, %Y").replace(tzinfo=zoneMapping[z])

KeyError: 'WTF'
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
0

Did you check the documentation at all?

dt_o = dt.strptime(date, '%b %d, %Y %Z')
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30