Python Forum

Full Version: What time format is this?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm working with an API that returns the time for events in this format:

2022-06-14T13:00:00-07:00

Can I presume that that's telling me local time with the UTC offset (-07:00) appended to it? Or would it be UTC with the offset included to produce local time?

This fails with "ValueError: 'z' is a bad directive in format '%Y-%m-%dT%H:%M:%S%z'":

datetime.datetime.strptime("2022-06-14T13:00:00-07:00", '%Y-%m-%dT%H:%M:%S%z')

I can chop off the offset easily enough, but I'm wondering if that's the best approach.

Thanks for any insights.
There is a package (i just tested it for the first time, but it did what I wanted).
python-dateutil: https://pypi.org/project/python-dateutil/

here's a simple test using your date format.
from dateutil.parser import parse


now = parse("2022-06-14T13:00:00-07:00")
print(f"now: {now}")
today = now.date()
print(f"today is: {today}")
results:
Output:
now: 2022-06-14 13:00:00-07:00 today is: 2022-06-14
It looks like an ISO-8601 time format. Look at datetime.datetime.fromisoformat()
Pendulum make it easier,and it dos Timezones right.
No need to mess together 3-4 libraries to get stuff to work,eg datetime, pytz, tzdata, zoneinfo, dateutil...ect.
>>> import pendulum
>>> 
>>> d = '2022-06-14T13:00:00-07:00'
>>> dt = pendulum.parse(d, strict=False)
>>> dt
DateTime(2022, 6, 14, 13, 0, 0, tzinfo=Timezone('-07:00'))
>>> # Or
>>> dt.fromisoformat(d)
DateTime(2022, 6, 14, 13, 0, 0, tzinfo=UTC-07:00)
>>> 
>>> dt.to_iso8601_string()
'2022-06-14T13:00:00-07:00'
>>> dt.to_datetime_string()
'2022-06-14 13:00:00'
>>> dt.to_formatted_date_string()
'Jun 14, 2022'
>>> dt.to_rfc850_string()
'Tuesday, 14-Jun-22 13:00:00 -07:00'