Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a datetime.date object into datetime.datetime in python? [duplicate]

Possible Duplicate:
Convert a datetime.date object into a datetime.datetime object with zeros for any missing time attributes

How do I convert a datetime.date obj into datetime.datetime obj, defaulting to midnight?

like image 854
user1008636 Avatar asked Jul 23 '12 19:07

user1008636


People also ask

How do you convert a date object to a datetime object in Python?

Using the datetime() Pass the year, month and day values of the desired date object (as my_date. year, my_date. month, my_date. day) to this constructor to convert a date object to datetime object.

How do I change the format of a datetime object?

Use strftime() function of a datetime class Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime.

How do I Stringify a date in Python?

Convert this datetime object to string in format 'DD-MMM-YYYY (HH:MM:SS:MICROS)' i.e. Format string used here is “%d-%b-%Y (%H:%M:%S. %f)“. The format string contains the codes pointing to each element of datetime like %d for day of month & %Y for year etc.

What is datetime datetime now () in Python?

Here, we have used datetime.now() to get the current date and time. Then, we used strftime() to create a string representing date and time in another format.


1 Answers

Use the datetime.combine method with an empty time instance:

dateobject = datetime.date.today()
datetime.datetime.combine(dateobject, datetime.time())

Alternatively, you can use the datetime.time.min constant:

datetime.datetime.combine(dateobject, datetime.time.min)

Both datetime.time() and datetime.time.min represent midnight (00:00:00).

like image 91
Martijn Pieters Avatar answered Oct 13 '22 23:10

Martijn Pieters