Home > python > Convert a date string to a date object

Convert a date string to a date object

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.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: