Title: Date And Time Basics
Slug: date_and_time_basics
Summary: Date And Time Basics
Date: 2016-05-01 12:00
Category: Python
Tags: Basics
Authors: Chris Albon


In [24]:
# Import modules
from datetime import datetime
from datetime import timedelta

In [25]:
# Create a variable with the current time
now = datetime.now()
now


Out[25]:
datetime.datetime(2014, 5, 11, 20, 5, 11, 688051)

In [26]:
# The current year
now.year


Out[26]:
2014

In [27]:
# The current month
now.month


Out[27]:
5

In [28]:
# The current day
now.day


Out[28]:
11

In [29]:
# The current hour
now.hour


Out[29]:
20

In [30]:
# The current minute
now.minute


Out[30]:
5

In [37]:
# The difference between two dates
delta = datetime(2011, 1, 7) - datetime(2011, 1, 6)
delta


Out[37]:
datetime.timedelta(1)

In [38]:
# The difference days
delta.days


Out[38]:
1

In [39]:
# The difference seconds
delta.seconds


Out[39]:
0

In [35]:
# Create a time
start = datetime(2011, 1, 7)

In [36]:
# Add twelve days to the time
start + timedelta(12)


Out[36]:
datetime.datetime(2011, 1, 19, 0, 0)