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?
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With