Importing Packages in Python and Datetime

© QuantSprout

Let's import a package

import datetime as dt

Use ipython magic to see function options. Type datetime. and press tab. Highlight time and press enter. Hit shift-tab

dt.time

Use a function from the datetime package

print (dt.time(1))
01:00:00

Datetime Package

Use the now function to get the current datetime stamp.

ts_now = dt.datetime.now()
print (ts_now)
2016-06-23 12:43:17.660604

Extract the day from the timestamp

print (ts_now.day)
23

Extract some other datetime elements

print ts_now.year
print ts_now.month
print ts_now.minute
print ts_now.second
2016
6
27
53

Create a timestamp for Christmas

ts_xmas = dt.datetime(2016,12,25)
print ts_xmas
2016-12-25 00:00:00

Do math with the timestamps

ts_diff = ts_xmas - ts_now
print ts_diff
print type(ts_diff)
202 days, 8:32:06.348054
<type 'datetime.timedelta'>

Convert a string to datetime format

date_str = "01-10-2015"
date_ts = dt.datetime.strptime(date_str,"%m-%d-%Y")
print date_ts
print type(date_ts)
2015-01-10 00:00:00
<type 'datetime.datetime'>

Convert a datetime object to a string

new_date_str = dt.datetime.strftime(date_ts,"%H:%M:%S %m-%d-%Y")
print new_date_str
print type(new_date_str)
00:00:00 01-10-2015
<type 'str'>

Exercises

Create a variable called future with a datetime value of January 15, 2017 at 5:30pm

future = dt.datetime(2017,1,15,17,30,15,1)
print future
2017-01-15 17:30:15.000001

Create a variable with a timedelta equal to the difference between future and now

td = future - dt.datetime.now()
print td
224 days, 1:59:59.722890

Print the number of seconds from the timedelta

print td.total_seconds()
print td
print td.seconds
print td.days
print td.days*24*60*60 + td.seconds
19360941.2733
224 days, 2:02:21.273336
7341
224
19360941
td.total_seconds()%60
59.72289000079036

Bonus:

Try converting strings to datetime objects and datetime objects back to strings. What are some interesting datetime formats you can find in the documentation?

example = dt.datetime(2017,12,15,17,30)

print dt.datetime.strftime(example,'%m/%d/%y')
print dt.datetime.strftime(example,'%b-%d-%Y')
print dt.datetime.strftime(example,'%H:%M:%S')
print dt.datetime.strftime(example,'%B %d, %Y')
print dt.datetime.strftime(example,'%a %I %p')
print dt.datetime.strftime(example,'%U')
12/15/17
Dec-15-2017
17:30:00
December 15, 2017
Fri 05 PM
50