Home > Back-end >  python datetime %d causes problems
python datetime %d causes problems

Time:04-01

I'm trying to work with dates and datetime

from datetime import date,datetime

d1 = datetime.strptime('2008-03-03','%y-%m-%d')  //the %d is colored different!
d2 = datetime(2008, 2 ,3)

print(date.today())
print(d1 - d2)

error:

time data '2008-03-03' does not match format '%y-%m-%d'

What I'm doing wrong? The name of the file is test.py. Thats the woule file, and I run it with rightclick in VScode 'run python file in terminal'

CodePudding user response:

You must write %Y not %y, Then the code becomes

d1 = datetime.strptime('2008-03-03','%Y-%m-%d')

CodePudding user response:

The problem is with the %y...

%y Year without century as a zero-padded decimal number. 00, 01, ...

99 %-y Year without century as a decimal number. 0, 1, ..., 99

%Y Year with century as a decimal number. 2013, 2019 etc.

I've fiddled your code on https://www.mycompiler.io/view/B6EhAzCnd83, with the fix:

from datetime import date,datetime

d1 = datetime.strptime('2008-03-03','%Y-%m-%d')
d2 = datetime(2008, 2 ,3)

print(date.today())
print(d1 - d2)

outputs:

2022-04-01 29 days, 0:00:00

[Execution complete with exit code 0]

  • Related