Showing posts with label python timedelta add time hours minutes seconds datetime. Show all posts
Showing posts with label python timedelta add time hours minutes seconds datetime. Show all posts

Thursday, July 17, 2014

How to add time

Code
from datetime import datetime, timedelta                   #1
datetime.now()                                             #2
datetime.now() + timedelta(hours=10)                       #3
datetime.now() + timedelta(minutes=10)                     #4
datetime.now() + timedelta(seconds=10)                     #5


How this works - Line by Line

from datetime import datetime, timedelta             #1

Imports the datetime and timedelta classes from the datetime module

datetime.now()                                       #2
 
This returns a datetime object with the current time.

datetime.now() + timedelta(hours=10)                 #3
 
This returns a datetime object with the current time + 10 hours. 

The remaining lines should be self explanatory.  Interestingly, the timedelta class also allows you to add by days and weeks, but not by months or years.