Python Programming
Class 8
Date and Time
Unix epoch
Is the number of seconds that have elapsed since January 1, 1970 in UTC.
>> date +%s
1517710580
Python Native
time(), datetime(), dateutil()
import time
# time.time() returns the number of seconds
# since the epoch, as seconds.
print(time.time())
ts = time.time()
#Convert to a string that is human readable.
import datetime
st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
print(st)
#date_time functions
print(datetime.datetime.now())
print(datetime.datetime.now().isoformat())
print(datetime.datetime.now().utcnow())
Python Native
time(), datetime(), dateutil()
"""
date_time objects
"""
#Build a datetime using datetime
import datetime
datetime.datetime(year=2018, month=2, day=5,hour = 11,minute = 12,second = 40)
#Parse dates with dateutil from string formats
from dateutil import parser
date = parser.parse("2018-02-05 22:46:34")
NumPy’s datetime64
The datetime64 dtype encodes dates as 64-bit integers, and thus allows arrays of dates to be represented very compactly.
import numpy as np
date = np.array('2018-02-05', dtype=np.datetime64)
date
# vectorized operations
date + np.arange(7)
Pandas Timestamp object
Pandas provides a Timestamp object NumPy-style vectorized operations directly on this same object.
import pandas as pd
date = pd.to_datetime("2018-02-03 22:46:34")
date
date.strftime('%A')
#We can do NumPy-style vectorized operations directly on this sameobject
date + pd.to_timedelta(np.arange(12), 'D')
Pandas Time Series: Indexing by Time
index = pd.DatetimeIndex(['2018-02-03', '2018-02-04','2018-02-05', '2018-02-06'])
data = pd.Series([100, 50, 150, 400], index=index)
data
The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text.
-
Matplotlib is a multiplatform data visualization library built on NumPy arrays, and designed to work with the broader SciPy stack.
-
It was conceived by John Hunter in2002, originally as a patch to IPython for enabling interactive MATLAB-style plotting via gnu plot from the IPython command line.
-
Plotting package of choice of the Space Telescope Science Institute (Hubble Telescope).
More information: http://pbpython.com/effective-matplotlib.html
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
Bike example
Open Jupyter Notebook.
Challenge
See on Evernote
Resources
Python-Programming [Class 8]
By Jose Arrieta
Python-Programming [Class 8]
Date and Time, Unix epoch, time(), datetime(), dateutil(), NumPy’s datetime64, Pandas Timestamp object, Pandas Time Series: Indexing by Time, Jupyter, Matplotlib,
- 6,306