D
D
Danil Samodurov2020-09-21 21:32:48
Python
Danil Samodurov, 2020-09-21 21:32:48

Why does the strptime method from the datetime module add the year, month, and day if the format string doesn't have them?

Hello. There is such a code

from datetime import datetime

    print(datetime.strptime('23:14:44', '%H:%M:%S'))

the output will be: datetime.datetime(1900, 1, 1, 23, 14, 44). Question: where did the year, month and day come from, if this was not in the specified format and how to remove them from the output?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
shurshur, 2020-09-21
@samodurOFF

The datetime object always has a year and everything else, by design. If they are not needed, you just need to format the output without them explicitly.

M
Maxim, 2020-09-21
@Tomio

You are using a "date-time" object, which means that your output must have a date and must have a time. And since no date was found in the input data, the default date is substituted.
To return a time object, you need to extract it from a datetime:

print(datetime.strptime('23:14:44', '%H:%M:%S').time())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question