How to calculate datetime in Python

How can I 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 about "How to calculate datetime in Python".


How to calculate datetime in Python

How to calculate datetime in Python

In order to calculate datetime in Python, we can use timedelta with datetime module.

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

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 parameters about "months" or "years".

If I want to add 1 year, I have to use days=365.


Today I described about "How to calculate datetime in Python".

Important points are following.

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

Once we understand timedelta, we can calculate datetime values in Python.

いいね または フォローしてね!

If you like this article, please share !
  • URLをコピーしました!
  • URLをコピーしました!


karasanのアバター karasan System engineer

Mid-career engineer (AI, Data science, Salesforce, etc.).
Good at Python and SQL.