Skip to content

Instantly share code, notes, and snippets.

#Importing the required modules
from datetime import datetime
from datetime import timedelta
#Printing the current date and timecurrent_time = datetime.now()
current_time
#Calculating the difference between two dates (14/02/2018 and 01/01/2018 09:15AM)
delta = datetime(2018,2,14)-datetime(2018,1,1,9,15)
delta
#Converting the output to days
delta.days
#Converting the output to seconds
delta.seconds
#Converting the output to seconds
delta.seconds
#Shift a date using timedelta
my_date = datetime(2018,2,10)
#Shift the date by 10 days
my_date + timedelta(10)
#Using multiples of timedelta function
my_date - 2*timedelta(10)
#Converting datetime to string
my_date1 = datetime(2018,2,14)
str(my_date1)
#Converting a string to datetime
datestr = '2018-02-14'
datetime.strptime(datestr, '%Y-%m-%d')