Combining parsed time with today's date in Python

It should be easy, but as always, Python's wildly overly complex datetime mess makes simple things complicated ...

So, I have a temporary line in the format HH: MM (for example, '09: 30 '), which I would like to include in the date and date with today's date. Unfortunately, the default date is January 1, 1900:

>>> datetime.datetime.strptime(time_str, "%H:%M") datetime.datetime(1900, 1, 1, 9, 50) 

datetime.combine looks like it meant exactly that, but I'll be damned if I can figure out how to get the time analyzed so it will take it:

 now = datetime.datetime.now() >>> datetime.datetime.combine(now, time.strptime('09:30', '%H:%M')) TypeError: combine() argument 2 must be datetime.time, not time.struct_time >>> datetime.datetime.combine(now, datetime.datetime.strptime('09:30', '%H:%M')) TypeError: combine() argument 2 must be datetime.time, not datetime.datetime >>> datetime.datetime.combine(now, datetime.time.strptime('09:30', '%H:%M')) AttributeError: type object 'datetime.time' has no attribute 'strptime' 

This monster is working ...

 >>> datetime.datetime.combine(now, datetime.time(*(time.strptime('09:30', '%H:%M')[3:6]))) datetime.datetime(2014, 9, 23, 9, 30) 

... but there should be a better way to do this ...!?

+5
source share
2 answers

The signature says:

 datetime.combine(date, time) 

so pass the datetime.date object as the first argument, and the datetime.time object as the second argument:

 >>> import datetime as dt >>> today = dt.date.today() >>> time = dt.datetime.strptime('09:30', '%H:%M').time() >>> dt.datetime.combine(today, time) datetime.datetime(2014, 9, 23, 9, 30) 
+11
source

pip install python-dateutil

 >>> from dateutil import parser as dt_parser >>> dt_parser.parse('07:20') datetime.datetime(2016, 11, 25, 7, 20) 

https://dateutil.readthedocs.io/en/stable/parser.html

+1
source

Source: https://habr.com/ru/post/1203223/


All Articles