Eugene
Eugene

Reputation: 13

Datetime can't take year below 1000

For example print(days_diff((1000, 1, 1), (9999, 12, 31))) - works fine, but print(days_diff((100, 1, 1), (9999, 12, 31))) - says that - "time data '(100, 1, 1)' does not match format '(%Y, %m, %d)'". How to solve it?

from datetime import datetime as dt

def days_diff(d1, d2):

    d1 = dt.strptime(str(d1), "(%Y, %m, %d)")
    d2 = dt.strptime(str(d2), "(%Y, %m, %d)")

    return abs((d2 - d1).days)

Upvotes: 0

Views: 297

Answers (2)

xjcl
xjcl

Reputation: 15319

What you are doing is turning the tuple into a str and then parsing that into a datetime. But you can also pass your (year, month, day) tuple directly to the datetime constructor:

from datetime import datetime as dt

def days_diff(d1, d2):

    d1 = dt(*d1)
    d2 = dt(*d2)

    return abs((d2 - d1).days)

# result: 3615899
print( days_diff((100,1,1), (9999,12,31)) )```

Upvotes: 2

Lukas Thaler
Lukas Thaler

Reputation: 2720

%Y denotes a year in yyyy-format. When providing a three-digit-number, that criterion is not met. You'll need to pad your year with leading zeroes to make it match the format, e.g. dt.strptime('(0999, 12, 12)', "(%Y, %m, %d)") will convert to a valid datetime no problem. EDIT: for a better way to do the conversion see xjcl's answer. Leaving this up to explain the error

Upvotes: 1

Related Questions