Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format date in ISO using Python?

Tags:

python

date

iso

I have some dates which format is d/m/yyyy (e.g. 2/28/1987). I would like to have it in the ISO format : 1987-02-28

I think we can do it that way, but it seems a little heavy:

str_date = '2/28/1987'
arr_str = re.split('/', str_date)
iso_date = arr_str[2]+'-'+arr_str[0][:2]+'-'+arr_str[1]

Is there another way to do it with Python?

like image 555
Reveclair Avatar asked Oct 07 '12 19:10

Reveclair


2 Answers

You could use the datetime module:

datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()

or, as running code:

>>> import datetime
>>> str_date = '2/28/1987'
>>> datetime.datetime.strptime(str_date, '%m/%d/%Y').date().isoformat()
'1987-02-28'
like image 118
Martijn Pieters Avatar answered Oct 11 '22 23:10

Martijn Pieters


I would use the datetime module to parse it:

>>> from datetime import datetime
>>> date = datetime.strptime('2/28/1987', '%m/%d/%Y')
>>> date.strftime('%Y-%m-%d')
'1987-02-28'
like image 38
Blender Avatar answered Oct 11 '22 23:10

Blender