w3resource

Python: Convert the date to datetime (midnight of the date)


8. Date to Midnight Datetime

Write a Python program to convert the date to datetime (midnight of the date) in Python.

Sample Solution:

Python Code:

# Import the date class from the datetime module
from datetime import date
# Import the datetime class from the datetime module
from datetime import datetime

# Get the current date and assign it to the variable 'dt'
dt = date.today()

# Combine the current date 'dt' with the minimum time value (00:00:00) of a datetime object
# This effectively creates a datetime object with the date component from 'dt' and the time component as the minimum possible time
# Print the resulting datetime object
print(datetime.combine(dt, datetime.min.time()))

Output:

2017-05-06 00:00:00  

Explanation:

In the exercise above,

  • The code imports the "date" class and the "datetime" class from the "datetime" module.
  • Get Current Date:
    • It retrieves the current date using the "date.today()" method and assigns it to the variable "dt".
  • Combining Date and Time:
    • It combines the current date "dt" with the minimum possible time value (00:00:00) of a datetime object using the "datetime.combine()" method.
    • This effectively creates a datetime object with the date component from "dt" and the time component as the minimum possible time.
  • Finally it prints the resulting datetime object, which represents the current date with the time component set to the minimum possible time (midnight).

Flowchart:

Flowchart: Convert the date to datetime (midnight of the date).

For more Practice: Solve these Related Problems:

  • Write a Python program to convert a given date to a datetime object set at midnight and then format it as "YYYY-MM-DD 00:00:00".
  • Write a Python function that takes a date string and returns the corresponding datetime at 00:00:00, discarding any time information.
  • Write a Python script to convert today's date to a datetime with time set to midnight and then add a 12-hour offset.
  • Write a Python program that converts a date to midnight and then calculates the number of seconds since midnight.

Go to:


Previous: Write a Python program to print yesterday, today, tomorrow.
Next: Write a Python program to print next 5 days starting from today.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.