0% found this document useful (0 votes)
61 views27 pages

Chapter4-Handling Dates and Times

This document discusses Python datetime types and libraries for working with datetimes. It introduces the datetime module and shows how to parse strings into datetime objects. It demonstrates extracting datetime components like year, month, and day. It also covers converting between timezones and calculating datetime differences using timedelta. The document recommends the pendulum library for easier parsing and manipulation of datetimes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views27 pages

Chapter4-Handling Dates and Times

This document discusses Python datetime types and libraries for working with datetimes. It introduces the datetime module and shows how to parse strings into datetime objects. It demonstrates extracting datetime components like year, month, and day. It also covers converting between timezones and calculating datetime differences using timedelta. The document recommends the pendulum library for easier parsing and manipulation of datetimes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

There and Back

Again a DateTime
Journey
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N

Jason Myers
Instructor
From string to datetime
The datetime module is part of the Python standard library

Use the datetime type from inside the datetime module

.strptime() method converts from a string to a datetime


object

from datetime import datetime


print(parking_violations_date)

06/11/2016

DATA TYPES FOR DATA SCIENCE IN PYTHON


Parsing strings into datetimes
date_dt = datetime.strptime(parking_violations_date,
'%m/%d/%Y')
print(date_dt)

2016-06-11 00:00:00

DATA TYPES FOR DATA SCIENCE IN PYTHON


Time Format Strings
Directive Meaning Example
Day of the month as a zero-
%d 01, 02, ..., 31
padded decimal number.
Month as a zero-padded
%m 01, 02, ..., 12
decimal number.
Year with century as a 0001, 0002, ..., 2013,
%Y
decimal number. 2014, ..., 9998, 9999

Full list available in the Python documentation

DATA TYPES FOR DATA SCIENCE IN PYTHON


Datetime to String
.strftime() method uses a format string to convert a
datetime object to a string

date_dt.strftime('%m/%d/%Y')

'06/11/2016'

isoformat() method outputs a datetime as an ISO standard


string

date_dt.isoformat()

'2016-06-11T00:00:00'

DATA TYPES FOR DATA SCIENCE IN PYTHON


Let's practice!
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N
Working with
Datetime
Components and
current time
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N

Jason Myers
Instructor
Datetime Components
day , month , year , hour , minute , second , and more are
available from a datetime instance

Great for grouping data

daily_violations = defaultdict(int)
for violation in parking_violations:
violation_date = datetime.strptime(violation[4],
'%m/%d/%Y')
daily_violations[violation_date.day] += 1

DATA TYPES FOR DATA SCIENCE IN PYTHON


Datetime Components - Results
print(sorted(daily_violations.items()))

[(1, 80986), (2, 79831), (3, 74610), (4, 69555),


(5, 68729), (6, 76232),(7, 82477), (8, 72472),
(9, 80415), (10, 75387), (11, 73287), (12, 74614),
(13, 75278), (14, 81803), (15, 79122), (16, 80692),
(17, 73677), (18, 75927), (19, 80813), (20, 80992),
(21, 78138), (22, 81872), (23, 78104), (24, 63490),
(25, 78898), (26, 78830), (27, 80164), (28, 81954),
(29, 80585), (30, 65864), (31, 44125)]

DATA TYPES FOR DATA SCIENCE IN PYTHON


What is the deal with now
.now() method returns the current local datetime

.utcnow() method returns the current UTC datetime

from datetime import datetime


local_dt = datetime.now()
print(local_dt)

2017-05-05 12:30:00.740415

DATA TYPES FOR DATA SCIENCE IN PYTHON


What is the deal with utcnow
utc_dt = datetime.utcnow()
print(utc_dt)

2017-05-05 17:30:05.467221

DATA TYPES FOR DATA SCIENCE IN PYTHON


Timezones
Naive datetime objects have no timezone data

Aware datetime objects have a timezone

Timezone data is available via the pytz module via the


timezone object

Aware objects have .astimezone() so you can get the time


in another timezone

DATA TYPES FOR DATA SCIENCE IN PYTHON


Timezones in action
from pytz import timezone
record_dt = datetime.strptime('07/12/2016 04:39PM',
...: '%m/%d/%Y %H:%M%p')
ny_tz = timezone('US/Eastern')
a_tz = timezone('US/Pacific')
ny_dt = record_dt.replace(tzinfo=ny_tz)
la_dt = ny_dt.astimezone(la_tz)

DATA TYPES FOR DATA SCIENCE IN PYTHON


Timezones in action - results
print(ny_dt)

2016-07-12 04:39:00-04:00

print(la_dt)

2016-07-12 01:39:00-07:00

DATA TYPES FOR DATA SCIENCE IN PYTHON


Let's practice!
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N
Time Travel (Adding
and Subtracting
Time)
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N

Jason Myers
Instructor
Incrementing through time
timedelta is used to represent an amount of change in time

Used to add or subtract a set amount of time from a datetime


object

from datetime import timedelta


flashback = timedelta(days=90)
print(record_dt)

2016-07-12 04:39:00

DATA TYPES FOR DATA SCIENCE IN PYTHON


Adding and subtracting timedeltas
print(record_dt - flashback)

2016-04-13 04:39:00

print(record_dt + flashback)

2016-10-10 04:39:00

DATA TYPES FOR DATA SCIENCE IN PYTHON


Datetime differences
Use the - operator to calculate the di erence

Returns a timedelta with the di erence

time_diff = record_dt - record2_dt


type(time_diff)

datetime.timedelta

print(time_diff)

0:00:04

DATA TYPES FOR DATA SCIENCE IN PYTHON


Let's practice!
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N
HELP! Libraries to
make it easier
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N

Jason Myers
Instructor
Parsing time with pendulum
.parse() will a empt to convert a string to a pendulum
datetime object without the need of the format string

import pendulum

occurred = violation[4] + ' ' + violation[5] +'M'

occurred_dt = pendulum.parse(occurred, tz='US/Eastern')

print(occured_dt)

'2016-06-11T14:38:00-04:00'

DATA TYPES FOR DATA SCIENCE IN PYTHON


Timezone hopping with pendulum
.in_timezone() method converts a pendulum time object to
a desired timezone.

.now() method accepts a timezone you want to get the


current time in

print(violation_dts)

[<Pendulum [2016-06-11T14:38:00-04:00]>,
<Pendulum [2016-04-25T14:09:00-04:00]>,
<Pendulum [2016-04-23T07:49:00-04:00]>,
<Pendulum [2016-04-26T07:09:00-04:00]>,
<Pendulum [2016-01-04T09:52:00-05:00]>]

DATA TYPES FOR DATA SCIENCE IN PYTHON


More timezone hopping
for violation_dt in violation_dts:
print(violation_dt.in_timezone('Asia/Tokyo'))

2016-06-12T03:38:00+09:00
2016-04-26T03:09:00+09:00
2016-04-23T20:49:00+09:00
2016-04-26T20:09:00+09:00
2016-01-04T23:52:00+09:00

print(pendulum.now('Asia/Tokyo'))

<Pendulum [2017-05-06T08:20:40.104160+09:00]>

DATA TYPES FOR DATA SCIENCE IN PYTHON


Humanizing differences
.in_XXX() methods provide the di erence in a chosen
metric

.in_words() provides the di erence in a nice expressive


form

diff = violation_dts[3] - violation_dts[2]


diff

<Period [2016-04-26T07:09:00-04:00 ->


2016-04-23T07:49:00-04:00]>

print(diff.in_words())

'2 days 23 hours 20 minutes'

DATA TYPES FOR DATA SCIENCE IN PYTHON


More human than human
print(diff.in_days())

print(diff.in_hours())

71

DATA TYPES FOR DATA SCIENCE IN PYTHON


Let's practice!
D ATA T Y P E S F O R D ATA S C I E N C E I N P Y T H O N

You might also like