parsing date string in python (convert string to date) - python

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)

Related

Converting dates in Python

I have dates in the form 26/11/2015. How can I convert them into the format 26-Nov-2015 and still keep them as dates and not strings?
Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.
So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:
>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'
Conversely, use strptime to parse strings in different formats to dates:
>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)
from datetime import datetime
date = datetime.strptime('26/11/2015', '%d/%m/%Y')
print date.strftime("%d-%B-%Y")
In the above example, we are taking your input string 'dd/mm/yyyy' and turning it into a python datetime saving it to a variable called date (for future usage as per your request), and then printing it out in the format requested.
You want to use the datetime module I think. For example:
from datetime import date
a = date(2015, 11, 26)
a.strftime("%A %d of %B, %Y")
should give you 'Thursday 26 of November, 2015'
Or for your specific formatting request:
a.strftime("%d-%b-%Y") #'26-Nov-2015'
Hope this helps, good luck!

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?

Convert unicode to datetime proper strptime format

I am trying to convert a unicode object to a datetime object.
I read through the documentation: http://docs.python.org/2/library/time.html#time.strptime
and tried
datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%SZ')
but I get the error message ValueError: time data '2014-01-15T01:35:30.314Z' does not match format '%Y-%m-%dT%H:%M:%SZ'
Any feedback on what is the proper format?
I appreciate the time and expertise.
You can parse the microseconds:
from datetime import datetime
date_posted = '2014-01-15T01:35:30.314Z'
datetime.strptime(date_posted, '%Y-%m-%dT%H:%M:%S.%fZ')
One option is to let dateutil do the job:
>>> from dateutil import parser
>>> parser.parse('2014-01-15T01:35:30.314Z')
datetime.datetime(2014, 1, 15, 1, 35, 30, 314000, tzinfo=tzutc())

Convert UTC time to python datetime

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())

Categories