3

I am working with an API that is returning a JSON string that contains the following date/time in it:

2013-03-14T14:15:23-07:00 

I get the date and the time, down to the second. But the last 5 characters are confusing me. I'm guessing that's a UTC offset. (mountain time) What i can't figure out how to do is to compare the above string to a date/time in python. The T is also throwing me off.

How do I encode a python date/time string to match the above?

1
  • 1
    You're looking at isoformat Commented Feb 13, 2013 at 5:38

2 Answers 2

2

If you use the python-dateutil library (https://crate.io/packages/python-dateutil/) you can convert that value to a datetime.

>>> dateutil.parser.parse('2013-03-14T14:15:23-07:00') datetime.datetime(2013, 3, 14, 14, 15, 23, tzinfo=tzoffset(None, -25200)) 
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent! That's exactly what i needed. The only thing i'm stuck on now is trying to get the current datetime in an offset-aware format so i can compare the two. I'm still trying to wrap my head around how Python handles dates/times.
You should be able to use .replace(tzinfo=...) on your datetime. Giving it a time zone makes it aware, None makes it naive.
2

You are looking at ISO 8601 date format. You can use a package to parse it or do it yourself.

You can use datetime.strptime to parse:

>>> ts='2013-03-14T14:15:23-07:00' >>> datetime.datetime.strptime(ts[0:-6],'%Y-%m-%dT%H:%M:%S') datetime.datetime(2013, 3, 14, 14, 15, 23) 

Then just add/subtract the time delta (for a 'naive' object):

>>> datetime.timedelta(hours=int(ts[-6:-3])) datetime.timedelta(-1, 61200) 

so:

>>> d=datetime.datetime.strptime(ts[0:-6],'%Y-%m-%dT%H:%M:%S')+datetime.timedelta(hours=int(ts[-6:-3])) >>> d datetime.datetime(2013, 3, 14, 7, 15, 23) 

The tricky part is the TZ is optional and whether you add / subtract the time offset or set the timezone in the date object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.