Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What time format is this?
#1
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.
Reply
#2
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
Reply
#3
It looks like an ISO-8601 time format. Look at datetime.datetime.fromisoformat()
Reply
#4
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'
and rob101 like this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python date format changes to date & time 1418 4 624 Jan-20-2024, 04:45 AM
Last Post: 1418
Smile Set 'Time' format cell when writing data to excel and not 'custom' limors 3 6,324 Mar-29-2021, 09:36 PM
Last Post: Larz60+
  ValueError: time data 'None' does not match format '%Y-%m-%dT%H:%M:%S.%f' rajesh3383 4 14,630 Sep-03-2020, 08:22 PM
Last Post: buran
  how to retain time format in df.to_csv Mekala 2 3,188 Aug-07-2020, 07:04 AM
Last Post: buran
  getting error ValueError: time data '' does not match format '%H:%M' srisrinu 2 5,613 Apr-09-2020, 11:12 AM
Last Post: srisrinu
  Incorrect time format KoSik 5 3,059 Aug-15-2019, 05:10 PM
Last Post: KoSik
  Change Time Format in Python bluethundr 2 2,705 Mar-04-2019, 09:13 PM
Last Post: bluethundr
  Wrong or missing date format and time in mails sipriusPT 3 4,283 Aug-08-2017, 03:22 PM
Last Post: sipriusPT

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020