rivercity
rivercity

Reputation: 376

python datetime %d causes problems

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'

Upvotes: 2

Views: 1049

Answers (3)

rivercity
rivercity

Reputation: 376

It seems like it's an cosmetic problem:

https://github.com/microsoft/vscode/issues/133127

Code works now, no error, but highlighting is still off, even if I use Extension Bisect and deactivate all extensions, or manually deactivate all extensions.

VSCode 1.66

Upvotes: 0

Rhubenni Telesco
Rhubenni Telesco

Reputation: 249

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]

Upvotes: 1

Triki Sadok
Triki Sadok

Reputation: 135

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

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

Upvotes: 2

Related Questions