[Tutor] date conversion

Kent Johnson kent37 at tds.net
Wed Apr 5 16:50:33 CEST 2006


Ray Allen wrote:
> I would like Python to convert a date returned by MySQL (2006-04-05) to a 
> user readable format such as 05-Apr-2006 for display and then to convert it 
> back to ISO format for update.

Here's one way:

In [1]: from datetime import date

In [2]: data = '2006-04-05'

Use split() and int() to convert to a list of year, month, day
In [4]: ymd = map(int, data.split('-'))

In [5]: ymd
Out[5]: [2006, 4, 5]

Turn it into a date. The * makes the list act like individual parameters.
In [6]: d=date(*ymd)

In [7]: d
Out[7]: datetime.date(2006, 4, 5)

See the docs for the time module for info about strftime() format codes
In [8]: d.strftime('%d-%b-%Y')
Out[8]: '05-Apr-2006'

ISO format is built-in.
In [9]: d.isoformat()
Out[9]: '2006-04-05'


For other input formats you might have to use time.strptime() to convert 
to a time tuple, then pass the first three elements do date():

In [10]: import time

In [15]: t=time.strptime(data, '%Y-%m-%d')

In [16]: t
Out[16]: (2006, 4, 5, 0, 0, 0, 2, 95, -1)

In [17]: date(*t[:3])
Out[17]: datetime.date(2006, 4, 5)


Kent



More information about the Tutor mailing list