Search code examples
pythonstrptime

strptime with 3 character timezone and AM/PM


Based on the documentation for strptime, I believe my code is correct for a 3 character timezone and AM/PM.

Why does Python 2.5 and Python 3.6 not like the string time format I am using?

import datetime
ts = datetime.datetime.strptime(
    "11/30/2017 01:08:05 PM CST", 
    '%m/%d/%Y %I:%M:%S %p %z'
)

or

import datetime
ts = datetime.datetime.strptime(
    "11/30/2017 01:08:05 PM CST", 
    '%m/%d/%Y %I:%M:%S %p %Z'
)

When run both return:

ValueError: time data '11/30/2017 01:08:05 PM CST' does 
not match format '%m/%d/%Y %I:%M:%S %p %Z'

Solution

  • Symbolic timezones such as CST are not parsed by strptime. Furthery they are relatively meaningless. Is CST:

    • Central Standard Time; or
    • China Standard Time; or
    • Cuba Standard Time.

    To handle your situation you should consider using dateutil.parser, and giving it a tzinfo for the timezones you wish to support.