date reformatting

Magnus Lycka lycka at carmen.se
Tue Oct 11 09:36:31 EDT 2005


Bell, Kevin wrote:
> Anyone aware of existing code to turn a date string "8-15-05" into the
> number 20050815?

 >>> import datetime
 >>> s = "8-15-05"
 >>> month,day,year = map(int, s.split('-'))
 >>> date = datetime.date(2000+year,month,day)
 >>> date.strftime('%Y%m%d')
'20050815'

Of course, if you really want the *number* 20050815 you'd
have to do
 >>> int(date.strftime('%Y%m%d'))

Using a datetime.date object means that you have good
support for a lot of arithmetic on and formatting of
dates without writing a lot of new code.

If you really mean that you want the number 20050815, I
assume this is because some legacy system beyond you control
need to have dates in that format. It's not a particularly
good format for dates. If you just want a numeric storage of
dates, I'd suggest using datetime.date.toordinal/fromordinal.
Those numbers aren't as easy to decipher manually, but at
least they work right if you subtract dates or add or subtract
days from a date.



More information about the Python-list mailing list