Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there a built-in function that converts a datetime.date object into a datetime.datetime object with 0's for the missing stuff? For example, suppose

tdate = datetime.date(2012,1,31)

I want to write something like either of these

tdatetime = datetime.date.datetime()
tdatetime = datetime.datetime(tdate)

and I want the output to be

datetime.datetime(2012, 1, 31, 0, 0)

But neither works. There is a builtin function to go from datetime.datetime to datetime.date, but I'm looking for the reverse operation.

One very poor solution would be to write:

datetime.datetime(tdate.year(), tdate.month(), tdate.day(), 0, 0)

I specifically want to avoid this bad way of doing it.

I've already written my own small function to do this, but I think it should be provided in the module. It's cluttering up some system-wide imports to use my function. It's workable, just not very Pythonic.

I'm just asking to see if anyone knows whether there is an efficient way to do it using only datetime module functions.

like image 397
ely Avatar asked Jun 25 '12 15:06

ely


People also ask

How do I format a datetime object in Python?

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. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

How do I convert datetime to date in Python?

For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt. date from Pandas in Python.

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.

What does datetime datetime NOW () do?

The . datetime. now() method returns a new datetime object with the current local date and timestamp.


1 Answers

Use .combine(date, time) with an empty time instance:

>>> import datetime
>>> tdate = datetime.date(2012,1,31)
>>> datetime.datetime.combine(tdate, datetime.time())
datetime.datetime(2012, 1, 31, 0, 0)

If you like to use a constant instead, use time.min:

>>> datetime.datetime.combine(tdate, datetime.time.min)
datetime.datetime(2012, 1, 31, 0, 0)
like image 60
Martijn Pieters Avatar answered Sep 30 '22 10:09

Martijn Pieters