How to calculate datetime in Python

Sometimes we would like to calculate datetime in Python.
Then we search like "Python date time calculate".
So today I introduce how to calculate datetime in Python.

datetime module

When we deal with date or time, we use datetime module.
If you want to set fixed date, you can set it in parameters.

import datetime

# Fixed datetime
dt1 = datetime.datetime(2019,11,19)
print(dt1)
# 2019-11-19 00:00:00

If you want to set current datetime, you can use now() method.

# Now
dt1 = datetime.datetime.now()
print(dt1)
# 2019-11-19 22:41:03.004331

timedelta

When we calculate date or time, we can use timedelta.
We can add or subtract fixed timedelta with datetime.

You can get 1 day later by adding datetime.timedelta(days=1) like below.

dt2 = dt1 + datetime.timedelta(days=1)
print(dt2)
# 2019-11-20 00:00:00

If you set hours=1 instead of days=1, you can get 1 hour later datetime.

dt2 = dt1 + datetime.timedelta(hours=1)
print(dt2)
# 2019-11-19 01:00:00

If you use minus (-), you can get 1 day before datetime.
You can get same result by adding days=-1.

# Subtract day
dt2 = dt1 - datetime.timedelta(days=1)
print(dt2)
# 2019-11-18 00:00:00

dt2 = dt1 + datetime.timedelta(days=-1)
print(dt2)
# 2019-11-18 00:00:00

Complex calculation You can set multiple parameters. So you can get complex calculation result like "1 day and 12 hours 10 minutes later".

dt2 = dt1 + datetime.timedelta(days=1, hours=12, minutes=10)
print(dt2)
# 2019-11-20 12:10:00

Other parameters are written in Python documents.

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
datetime — Basic date and time types — Python 3.8.0 documentation

There are no "months" and "years".

Finally

You can calculate datetime by using following items.

• Use datetime module to get fixed date or time.
• Use timedelta for calculation.

Translate »