Archive

Posts Tagged ‘date string’

Convert a date string to a date object

October 30, 2011 Leave a comment

Problem
I have a date string (‘Sat, 29 Oct 2011 18:32:56 GMT’) that I want to convert to a timestamp (‘2011_10_29’). I want to convert ‘Oct’ to ’10’ using the standard library, I don’t want to create a string array for this with the names of the months.

Solution

>>> from datetime import datetime
>>> s = 'Sat, 29 Oct 2011 18:32:56 GMT'
>>> s.split()[1:4]
['29', 'Oct', '2011']
>>> year, month, day = s.split()[1:4][::-1]
>>> year, month, day
('2011', 'Oct', '29')
>>> if len(day) == 1:
...     day = '0' + day
...   
>>> date = datetime.strptime("{yyyy} {Mmm} {dd}".format(yyyy=year, Mmm=month, dd=day), "%Y %b %d")
>>> template = "{year}_{month:02}_{day:02}"
>>> template.format(year=date.year, month=date.month, day=date.day)
'2011_10_29'

I used this conversion in this source code.

You can find the list of datetime formatting directives (%Y, %b, etc.) at the bottom of this page.