Basic datetime objects usage
suggest changeThe datetime module contains three primary types of objects - date, time, and datetime.
import datetime
# Date object
today = datetime.date.today()
new_year = datetime.date(2017, 1, 1) # datetime.date(2017, 1, 1)
# Time object
noon = datetime.time(12, 0, 0) #datetime.time(12, 0)
# Current datetime
now = datetime.datetime.now()
# Datetime object
millenium_turn = datetime.datetime(2000, 1, 1, 0, 0, 0) #datetime.datetime(2000, 1, 1, 0, 0)
Arithmetic operations for these objects are only supported within the same type, and arithmetic with instances of different types raises TypeError.
# subtraction of noon from today
noon - today
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.date'
However, it is straightforward to convert between types.
# Do this instead
print('Time since the millennium at midnight: ',
datetime.datetime(today.year, today.month, today.day) - millenium_turn)
# Or this
print('Time since the millennium at noon: ',
datetime.datetime.combine(today, noon) - millenium_turn)
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents