tags:

views:

180

answers:

3

I have MMDDYY dates, i.e. today is 111609

How do I convert this to 11/16/2009, in Python?

+13  A: 

I suggest the following:

import datetime
time = datetime.datetime.strptime("111609", "%m%d%y")
print time.strftime("%m/%d/%Y")

This will convert 010199 to 01/01/1999 and 010109 to 01/01/2009.

Tim Pietzcker
A: 
date = '111609'
new_date = date[0:2] + '/' + date[2:4] + '/' + date[4:6]
vgm64
Misses the four-digit year part. And what if the date is "010199"?
Tim Pietzcker
The question asked for a 4-figure year, not just the 2 figures from the original string
Ben James
Yep. Fail on my part. I only answered because it seemed like the OP wanted a hacked together answer. datetime ftw, imo.
vgm64
A: 
>>> s = '111609'
>>> d = datetime.date(int('20' + s[4:6]), int(s[0:2]), int(s[2:4]))
>>> # or, alternatively (and better!), as initially shown here, by Tim
>>> # d = datetime.datetime.strptime(s, "%m%d%y")
>>> d.strftime('%m/%d/%Y')
'11/16/2009'

one of the reasons why the strptime() approach is better is that it deals with dates close to contemporary times, with a window, i.e. properly handling dates in the latter part of the 20th century and dates in the early part of the 21st century properly.

mjv