Logo Questions Linux Laravel Mysql Ubuntu Git Menu

python convert single digit day and month to two digits

I'm trying to read and convert the following datetime "6/5/2014 00:09:32" to "Mon Mar 09 07:07:18 +0000 2015".

d = datetime.datetime.strptime('6/5/2014 00:09:32', '%d/%m/%y %H:%M:%S')

Gives me a traceback with:

ValueError: time data '6/5/2014 00:00:07' does not match format '%d/%m/%y %H:%M:%S'

I tried using %e for single digit days as suggested here: http://www.gnu.org/software/libc/manual/html_node/Formatting-Calendar-Time.html#index-strftime-2660, but datetime just says it doesn't recognize 'e'.

Unless I am missing something it looks like single digit days and months are my problem, but from the documentation (https://docs.python.org/2/library/time.html#time.strftime) I don't see a way to get python's datetime to read single digit days or months. But this seems silly. What am I missing?

Thank you for your help.

like image 393
Jeff Hemsley Avatar asked Mar 16 '23 07:03

Jeff Hemsley

1 Answers

You need 'Y' not 'y':

In [412]:

d = dt.datetime.strptime('6/5/2014 00:09:32', '%d/%m/%Y %H:%M:%S')
datetime.datetime(2014, 5, 6, 0, 9, 32)

From the docs 'Y' corresponds to:

Year with century as a decimal number.

You tried 'y' which is:

Year without century as a decimal number [00,99].

like image 198
EdChum Avatar answered Mar 31 '23 17:03