Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining a parsed time with today's date in Python

This should be easy, but as ever Python's wildly overcomplicated datetime mess is making simple things complicated...

So I've got a time string in HH:MM format (eg. '09:30'), which I'd like to turn into a datetime with today's date. Unfortunately the default date is Jan 1 1900:

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

datetime.combine looks like it's meant exactly for this, but I'll be darned if I can figure out how to get the time parsed so it'll accept 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 monstrosity works...

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

...but there must be a better way to do that...!?

like image 679
lambshaanxy Avatar asked Sep 23 '14 13:09

lambshaanxy


People also ask

How do I get the current date and time in Python?

Datetime module comes built into Python, so there is no need to install it externally. To get both current date and time datetime. now() function of DateTime module is used. This function returns the current local date and time.

What is datetime datetime now () in Python?

Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module. Parameters : tz : Specified time zone of which current time and date is required.


2 Answers

The function signature says:

datetime.combine(date, time)

so pass a datetime.date object as the first argument, and a 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)
like image 136
behzad.nouri Avatar answered Sep 23 '22 04:09

behzad.nouri


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

like image 23
madzohan Avatar answered Sep 20 '22 04:09

madzohan