Python date and time formatting

I am working with an API that returns a JSON string that contains the following date / time:

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

      

I am getting date and time, up to the second. But the last 5 characters confuse me. I am assuming UTC offset. (mountain time) What I can't figure out how to do is compare the above string with date / time in python. T also throws me off.

How to encode python date / time string as above?

+3


source to share


2 answers


If you are using the library python-dateutil

( https://crate.io/packages/python-dateutil/ ) you can convert this value to datetime

.



>>> dateutil.parser.parse('2013-03-14T14:15:23-07:00')
datetime.datetime(2013, 3, 14, 14, 15, 23, tzinfo=tzoffset(None, -25200))

      

+2


source


You're looking at the ISO 8601 date format . You can use the package to analyze 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 temporary 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 of TZ is optional and adds / subtracts the time offset or sets the timezone in the date object.

+2


source







All Articles