Convert UTC time to python datetime - python

I have numerous UTC time stamps in the following format:
2012-04-30T23:08:56+00:00
I want to convert them to python datetime objects but am having trouble.
My code:
for time in data:
pythondata[i]=datetime.strptime(time,"%y-%m-%dT%H:%M:%S+00:00")
I get the following error:
ValueError: time data '2012-03-01T00:05:55+00:00' does not match format '%y-%m-%dT%H:%M:%S+00:00'
It looks like I have the proper format, so why doesn't this work?

Change the year marker in your time format string to %Y:
time = '2012-03-01T00:05:55+00:00'
datetime.strptime(time, "%Y-%m-%dT%H:%M:%S+00:00")
# => datetime.datetime(2012, 3, 1, 0, 5, 55)
See strftime() and strptime() behavior.

I highly recommend python-dateutil library, it allows conversion of multiple datetime formats from raw strings into datetime objects with/without timezone set
>>> from dateutil.parser import parse
>>> parse('2012-04-30T23:08:56+00:00')
datetime.datetime(2012, 4, 30, 23, 8, 56, tzinfo=tzutc())

Related

convert 2021-01-18T11:18:10.833876+00:00 to datetime python

I am trying to convert the following string to datetime in python. After referring to datetime.strptime(‘2017-01-12T14:12:06.000-0500’,'%Y-%m-%dT%H:%M:%S.%f%Z') I am trying the below mentioned format.
config_current_ts = datetime.strptime(internal_config["timestamp_str"], "%Y:%m:%dT%H:%M:%S.%f%z")
Yet I get an error stating :
ValueError: time data '2021-01-18T11:18:10.833876+00:00' does not
match format '%Y:%m:%dT%H:%M:%S.%f%z'
I am using python3.7.4. Can someone tell me how to convert this to datetime? I want to basically compare the string and current time to see which is ahead.
With Python 3.7+, use fromisoformat - since you have ISO 8601 format, it is appropriate and as a benefit also more efficient. Ex:
from datetime import datetime
s = '2021-01-18T11:18:10.833876+00:00'
dt = datetime.fromisoformat(s)
print(dt)
# 2021-01-18 11:18:10.833876+00:00
print(repr(dt))
# datetime.datetime(2021, 1, 18, 11, 18, 10, 833876, tzinfo=datetime.timezone.utc)
the format string should be '%Y-%m-%dT%H:%M:%S.%f%z'
>>> from datetime import datetime
>>> d = '2021-01-18T11:18:10.833876+00:00'
>>> datetime.strptime(d, '%Y-%m-%dT%H:%M:%S.%f%z')
datetime.datetime(2021, 1, 18, 11, 18, 10, 833876, tzinfo=datetime.timezone.utc)

Why does the converting a dateutil rrule to a string and back make it lose its timezone information?

The dateutil.rrule module has an rrule class which has a custom __str__ method to convert its instances to strings, and a rrulestr function which does the opposite, namely, convert the string back to an object.
It seems, however, that the _dtstart attribute of the rrule loses its timezone information when converting to a string and back. For example, in the following script:
from dateutil.rrule import rrule, rrulestr, DAILY
from dateutil.parser import parse
start = parse("8 Feb 2017 14:00 UTC")
my_rrule = rrule(DAILY, dtstart=start)
my_rrule2 = rrulestr(str(my_rrule))
assert my_rrule._dtstart == my_rrule2._dtstart
the assertion leads to a
TypeError: can't compare offset-naive and offset-aware datetimes
Specifically, I noticed that my_rrule.dtstart has the representation
datetime.datetime(2017, 2, 8, 14, 0, tzinfo=tzutc())
whereas my_rrule2._dtstart is
datetime.datetime(2017, 2, 8, 14, 0)
Why is the timezone information lost? Is this not a deficiency in the __str__/rrulestr combination?

normalizing JSON datestrings to UTC python

I have an important test that says "Calculate users that logged in during the month of April normalized to the UTC timezone."
Items look as such:
[ {u'email': u' ybartoletti#littel.biz',
u'login_date': u'2014-05-08T22:30:57-04:00'},
{u'email': u'woodie.crooks#kozey.com',
u'login_date': u'2014-04-25T13:27:48-08:00'},
]
It seems to me that an item like 2014-04-13T17:12:20-04:00 means "April 13th, 2014, at 5:12:20 pm, 4 hours behind UTC". Then I just use strptime to convert to datetime (Converting JSON date string to python datetime), and subtract a timedelta of however many hours I get from a regex that grabs the end of string? I feel this way because some have a + at the end instead of -, like 2014-05-07T00:30:06+07:00
Thank you
It is probably best to use the dateutil.parser.parse and pytz packages for this purpose. This will allow you to parse a string and convert it to a datetime object with UTC timezone:
>>> s = '2014-05-08T22:30:57-04:00'
>>> import dateutil.parser
>>> import pytz
>>> pytz.UTC.normalize(dateutil.parser.parse(s))
datetime.datetime(2014, 5, 9, 2, 30, 57, tzinfo=<UTC>)
You can use arrow to easily parse date with time zone.
>>>import arrow
>>> a = arrow.get('2014-05-08T22:30:57-04:00').to('utc')
>>> a
<Arrow [2014-05-09T02:30:57+00:00]>
Get a datetime object or timestamp:
>>> a.datetime
datetime.datetime(2014, 5, 9, 2, 30, 57, tzinfo=tzutc())
>>> a.naive
datetime.datetime(2014, 5, 9, 2, 30, 57)
>>> a.timestamp
1399602657
The following solution should be faster and avoids importing external libraries. The downside is that it will only work if the date strings are all guaranteed to have the specified format. If that's not the case, then I would prefer Simeon's solution, which lets dateutil.parser.parse() take care of any inconsistencies.
import datetime as dt
def parse_date(datestr):
diff = dt.timedelta(hours=int(datestr[20:22]), minutes=int(datestr[23:]))
if datestr[19] == '-':
return dt.datetime.strptime(datestr[:19], '%Y-%m-%dT%H:%M:%S') - diff
return dt.datetime.strptime(datestr[:19], '%Y-%m-%dT%H:%M:%S') + diff

I want to parse string to timestamp-with-timezone in python

I try to parse string to time-stamp with timezone format.
here is an example
"2016-02-18 16:13:07+09"
i want to know parsing this string format to time-stamp format in python.
how can i do that?
Is the UTC offset format in your string +09 or +0900 ?
If the offset in your string is 0900 you can use the below .If your UTC offset is only +09 as you mentioned in your question , you can pad the string with 00 and get the below code to work .
Code:
import datetime
time="2016-02-18 16:13:07+0900"
new_time=datetime.datetime.strptime(time,"%Y-%m-%d %H:%M:%S%z")
print(new_time)
new_time_python=datetime.datetime.strftime(new_time,"%m-%d-%y")
print(new_time_python)
Output
2016-02-18 16:13:07+09:00
02-18-16
dateutil might be a suitable library for your purposes:
from dateutil.parser import parser
p = parser()
d = p.parse('2016-02-18 16:13:07+09'.decode('utf-8')) # must be unicode string
d
>>> datetime.datetime(2016, 2, 18, 16, 13, 7, tzinfo=tzoffset(None, 32400))
If the UTC offset may be specified both as +HH and +HHMM format then you could use str.ljust() method to normalize the input time string. Then you could use .strptime() to parse it:
#!/usr/bin/env python3
from datetime import datetime
time_string = "2016-02-18 16:13:07+09"
dt = datetime.strptime(time_string.ljust(24, "0"), "%Y-%m-%d %H:%M:%S%z")
# -> datetime.datetime(2016, 2, 18, 16, 13, 7,
# tzinfo=datetime.timezone(datetime.timedelta(0, 32400)))
If your Python version doesn't support %z, see How to parse dates with -0400 timezone string in python?

parsing date string in python (convert string to date)

I have a datetime string in the form of a string as:
2011-10-23T08:00:00-07:00
How do i parse this string as the datetime object.
I did the following reading the documentation:
date = datetime.strptime(data[4],"%Y-%m-%d%Z")
BUt I get the error
ValueError: time data '2011-10-23T08:00:00-07:00' does not match format '%Y-%m-%d%Z'
which is very clear.
But I am not sure how to read this format.
Any suggestions.
Thanks
Edit: Also, I must add, all I care about is the date part
Standard datetime.datetime.strptime has problems with timezone definitions. Use dateutil.parser
>>> from dateutil import parser
>>> parser.parse("2011-10-23T08:00:00-07:00")
datetime.datetime(2011, 10, 23, 8, 0, tzinfo=tzoffset(None, -25200))
If you care about the date part only, you can try it without dateutil.parser:
>>> from datetime import datetime
>>> datetime.strptime(data[4].partition('T')[0], '%Y-%m-%d').date()
datetime.date(2011, 10, 23)

Categories