Home > database >  Datetime not matching format
Datetime not matching format

Time:11-27

I'm trying to convert a string into a datetime. However is says that I don't follow the format and I am confused. Could anyone help me please?

Code:

from datetime import datetime
date = datetime.strptime('2021-11-27 00:00', '%y-%m-%d %H:%M')

Error:

ValueError: time data '2021-11-27 00:00' does not match format '%y-%m-%d %H:%M'

CodePudding user response:

The %y code matches a two-digit year - for a four-digit year, you should use %Y instead.

date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M')

CodePudding user response:

as per the documentation, %y is

Year without century as a zero-padded decimal number.

and %Y is

Year with century as a decimal number.

so

from datetime import datetime
date = datetime.strptime('2021-11-27 00:00', '%Y-%m-%d %H:%M')
date

will give datetime.datetime(2021, 11, 27, 0, 0)

CodePudding user response:

I'm not familiar with python too much but this documentation says %y is for year without century but %Y is for year with century:

Directive Meaning
%y Year without century as a zero-padded decimal number.
%Y Year with century as a decimal number.

So, looks like the correct format should be %Y-%m-%d %H:%M

Here a demonstration.

Remember, almost all programming languages have this custom specifiers and most of them are case sensitive.

  • Related