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.


1 comment:

  1. I love this post so much, it is so basic and straight forward.
    I was wondering if there is a chance to give the best common date format used on the deployed websites..
    Thanks again for the amazing website

    ReplyDelete