Convert date into datetime and reverse datetime into date objects in Python


This is a quick tips to convert “datetime” into “date” objects in Python:

1
2
3
4
5
from datetime import datetime
today = datetime.now()
print today
today_date = today.date()
print today_date

The result will be :

1
2
datetime.datetime(2012, 12, 6, 14, 48, 5, 133765)
datetime.date(2012, 12, 6)

Then, how about convert date into datetime objects? We need time() function:

1
2
3
4
5
6
from datetime import date, datetime, time

today = date.today()
print today
today_datetime = datetime.combine(today, time())
print today_datetime

And the result will be :

1
2
datetime.date(2012, 12, 6)
datetime.datetime(2012, 12, 6, 0, 0)

It easy! 😀


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.