Home > Software engineering >  OSError: [Errno 22] Invalid argument when using datetime.strptime
OSError: [Errno 22] Invalid argument when using datetime.strptime

Time:04-01

I tested the following code :

date_string = "16:30"
date = datetime.strptime(date_string, "%H:%M")
timestamp = datetime.timestamp(date)
print(timestamp)

But I got the error :

OSError: [Errno 22] Invalid argument

enter image description here

What should I do to get the timestamp of the time?

CodePudding user response:

Your code should work if you make the datetime object aware, i.e. set a time zone:

from datetime import datetime, timezone

date_string = "16:30"
date = datetime.strptime(date_string, "%H:%M").replace(tzinfo=timezone.utc)

print(date)
# 1900-01-01 16:30:00 00:00

print(date.timestamp())
# -2208929400.0

(Tested on Windows 10, Python 3.9.12)

CodePudding user response:

The error is that timestamp() doesn't have arguments (and it is exactly what the stack trace is telling you: Invalid argument.

I think you want date.timestamp(), so a method from your date variable (date is a datetime.datetime instance, and not the class datetime.date).

But I think you are importing datetime as from datetime import datetime. Do not do it. it will just confuse you and your editor, so you may get invalid suggestions from your IDE. And also do not use variable name date if you use datetime, but also in general, never use so generic variable names. It just confuse everything. Prefer a better variable name, e.g. a this_date or my_date (so nobody will confuse with datetime.date, especially if in future you need that clas). But better to set a better name.

  • Related