Python Forum

Full Version: Why does datetime.strptime() not work in this situation
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am relatively new to Python, and I am encountering a very strange issue. This is on python3.8. This really seems like a bug in python to me, but I am not skilled enough to make that determination for myself. The code as follows demonstrates the error:

from datetime import datetime as datetime
import pytz

TIMEZONE = pytz.timezone('America/Vancouver')
TZ=datetime.now(TIMEZONE).strftime("%Z")
combined_date = '24-12-2025 '+TZ
print(f"try = {combined_date}")
when = datetime.strptime(combined_date,'%d-%m-%Y %Z')
What happens is as follows:

Error:
try = 24-12-2025 PDT Traceback (most recent call last): File "a.py", line 10, in <module> when = datetime.strptime(combined_date,'%d-%m-%Y %Z') File "/usr/lib/python3.8/_strptime.py", line 568, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) File "/usr/lib/python3.8/_strptime.py", line 349, in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data '24-12-2025 PDT' does not match format '%d-%m-%Y %Z'
What is happening here? I never specified %r. Why is it complaining?

Unfortunately, I need this datetime to be established with a timezone. If I don't I get errors later on in my code complaining "TypeError: can't compare offset-naive and offset-aware datetimes"

Is this a bug, or am I doing something wrong? Is there another way to set the timezone that I should be using?
From the docs:
Quote:strptime() only accepts certain values for %Z:
  • any value in time.tzname for your machine’s locale
  • the hard-coded values UTC and GMT
So someone living in Japan may have JST, UTC, and GMT as valid values, but probably not EST. It will raise ValueError for invalid values.

do print(time.tzname) to check valid values in addition to UTC and GMT
The issue here is with parsing timezone information using strptime().
Python's strptime() has limited support for timezone parsing with %Z.
Can do it like this.
from datetime import datetime
import pytz

TIMEZONE = pytz.timezone('America/Vancouver')
date_str = '24-12-2025'
when = datetime.strptime(date_str, '%d-%m-%Y')
# Localize the datetime to the timezone
when = TIMEZONE.localize(when)

print(f"Date: {when}")
print(f"Timezone: {when.tzinfo}")
Output:
Date: 2025-12-24 00:00:00-08:00 Timezone: America/Vancouver
Or when dealing with Timezones use Pendulum.
Better API and Features and it's a drop-in replacement for Python's standard datetime.
import pendulum

when = pendulum.parse('2025-12-24', tz='America/Vancouver')
print(when)
Output:
2025-12-24 00:00:00-08:00