Parse a string to a date gives a wrong date

1.5k views Asked by At

I'm trying to parse a string to a date in this format : %Y%m%d%H%M%S by this code :

from dateutil.parser import parse as parseDate
from datetime import datetime, time, timedelta

chaine = "01/10/201604:45:00"
print chaine
date = chaine[:10] + " " + chaine[11:]
print date
date = parseDate(date,yearfirst=True)
print date
i = str(date).replace('-','')
print i
i = str(i).replace(':','')
print i
i = str(i).replace(' ','')
print i

This is what I get as output:

01/10/201604:45:00
01/10/2016 4:45:00
2016-01-10 04:45:00
20160110 04:45:00
20160110 044500
20160110044500

Here, instead of getting 01 as the day and 10 as the month, i get 01 as month and 10 as day, meaning I get january instead of october. In the other hand, when I change the chaine to : 14/11/201615:30:00 I get the correct date: 20161114053000 : month then day. Am I missing something here?

2

There are 2 answers

4
ettanany On BEST ANSWER

You can use datetime.strptime() to achieve that:

>>> from datetime import datetime
>>>
>>> datetime.strptime('01/10/201604:45:00', '%d/%m/%Y%H:%M:%S')
datetime.datetime(2016, 10, 1, 4, 45)
2
Martijn Pieters On

Your date is ambiguous; it can either be interpreted as the first of October or the 10th of January.

Because the first number in your input (01) is the day, not the month, you need to set the dayfirst argument to True; by default this is set to False, meaning the first number encountered is interpreted as the month:

>>> parseDate('01/10/2016 4:45:00')
datetime.datetime(2016, 1, 10, 4, 45)
>>> parseDate('01/10/2016 4:45:00', dayfirst=True)
datetime.datetime(2016, 10, 1, 4, 45)