How to calculate datetime in Python

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)
# 2019-11-19 00:00:00

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

# Now
dt1 =
# 2019-11-19 22:41:03.004331


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.

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

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

# Add hour
dt2 = dt1 + datetime.timedelta(hours=1)
# 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)
# 2019-11-18 00:00:00

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

Complex calculation

datetime complex calculation

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

# Add 1day 12hour 10minute
dt2 = dt1 + datetime.timedelta(days=1, hours=12, minutes=10)
# 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".


You can calculate datetime by using following items.

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

If you felt this article is useful, please share.

にほんブログ村 IT技術ブログへ


© 2023 ITips