Adding Dates and Times in Python

Mon, Oct 19, 2009

Tech Tips

Using the built-in modules datetime and timedelta, you can perform date and time addition/subtraction in python:

from datetime import datetime
from datetime import timedelta

#Add 1 day
print + timedelta(days=1)

#Subtract 60 seconds
print - timedelta(seconds=60)

#Add 2 years
print + timedelta(days=730)

#Other Parameters you can pass in to timedelta:
# days, seconds, microseconds, 
# milliseconds, minutes, hours, weeks

#Pass multiple parameters (1 day and 5 minutes)
print + timedelta(days=1,minutes=5)

Here is a python reference that gives more examples and advanced features:

If you are coming from a .net or sql environment, here are the above examples in C# and SQL (Microsoft) for comparison:

DateTime myTime = new DateTime();

--Add 1 day

--Subtract 60 seconds

--Add 2 years


--Add 1 day
select DATEADD(day, 1, getdate())

--Subtract 60 seconds
select DATEADD(second, -60, getdate())

--Add 2 years
select DATEADD(Year, 2, getdate())
Bookmark and Share
, ,

2 Responses to “Adding Dates and Times in Python”

  1. Brian Hansen Says:

    Pretty useless examples unless you’re actually doing some string conversion too.

  2. Tysonm Says:

    Great post, I believe blog owners should larn a lot from this website its really user friendly. So much good information on here :D.