0% found this document useful (0 votes)
6 views

py 9

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

py 9

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

VIDEO: Complete Python

Bootcamp: Go from zero

to hero in Python 3

Learn Python like a Professional! Start from the

basics and go all the way to creating your own

applications and games!

✔ Learn to use Python professionally, learning both Python 2 and Python 3!

✔ Create games with Python, like Tic Tac Toe and Blackjack!

✔ Learn advanced Python features, like the collections module and how to work with timestamps!

✔ Learn to use Object Oriented Programming with classes!

✔ Understand complex topics, like decorators.

✔ Understand how to use both the Jupyter Notebook and create .py files

✔ Get an understanding of how to create GUIs in the Jupyter Notebook system!

✔ Build a complete understanding of Python from the ground up!

Watch Today →

GoalKicker.com – Python® Notes for Professionals 42

Chapter 5: Date and Time

Section 5.1: Parsing a string into a timezone aware datetime

object

Python 3.2+ has support for %z format when parsing a string into a datetime object.

UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).

Python 3.x Version ≥ 3.2

import datetime

dt = datetime.datetime.strptime("2016-04-15T08:27:18-0500", "%Y-%m-%dT%H:%M:%S%z")

For other versions of Python, you can use an external library such as dateutil, which makes parsing a
string with

timezone into a datetime object is quick.

import dateutil.parser

dt = dateutil.parser.parse("2016-04-15T08:27:18-0500")

The dt variable is now a datetime object with the following value:

datetime.datetime(2016, 4, 15, 8, 27, 18, tzinfo=tzoffset(None, -18000))


Section 5.2: Constructing timezone-aware datetimes

By default all datetime objects are naive. To make them timezone-aware, you must attach a tzinfo
object, which

provides the UTC offset and timezone abbreviation as a function of date and time.

Fixed Offset Time Zones

For time zones that are a fixed offset from UTC, in Python 3.2+, the datetime module provides the
timezone class, a

concrete implementation of tzinfo, which takes a timedelta and an (optional) name parameter:

Python 3.x Version ≥ 3.2

from datetime import datetime, timedelta, timezone

JST = timezone(timedelta(hours=+9))

dt = datetime(2015, 1, 1, 12, 0, 0, tzinfo=JST)

print(dt)

# 2015-01-01 12:00:00+09:00

print(dt.tzname())

# UTC+09:00

dt = datetime(2015, 1, 1, 12, 0, 0, tzinfo=timezone(timedelta(hours=9), 'JST'))

print(dt.tzname)

# 'JST'

For Python versions before 3.2, it is necessary to use a third party library, such as dateutil. dateutil
provides an

equivalent class, tzoffset, which (as of version 2.5.3) takes arguments of the form
dateutil.tz.tzoffset(tzname,

offset), where offset is specified in seconds:

Python 3.x Version < 3.2

GoalKicker.com – Python® Notes for Professionals 43

Python 2.x Version < 2.7

from datetime import datetime, timedelta

from dateutil import tz

JST = tz.tzoffset('JST', 9 * 3600) # 3600 seconds per hour

dt = datetime(2015, 1, 1, 12, 0, tzinfo=JST)

print(dt)
# 2015-01-01 12:00:00+09:00

print(dt.tzname)

# 'JST'

Zones with daylight savings time

For zones with daylight savings time, python standard libraries do not provide a standard class, so it
is necessary to

use a third party library. pytz and dateutil are popular libraries providing time zone classes.

In addition to static time zones, dateutil provides time zone classes that use daylight savings time
(see the

documentation for the tz module). You can use the tz.gettz() method to get a time zone object, which
can then

be passed directly to the datetime constructor:

from datetime import datetime

from dateutil import tz

local = tz.gettz() # Local time

PT = tz.gettz('US/Pacific') # Pacific time

dt_l = datetime(2015, 1, 1, 12, tzinfo=local) # I am in EST

dt_pst = datetime(2015, 1, 1, 12, tzinfo=PT)

dt_pdt = datetime(2015, 7, 1, 12, tzinfo=PT) # DST is handled automatically

print(dt_l)

# 2015-01-01 12:00:00-05:00

print(dt_pst)

# 2015-01-01 12:00:00-08:00

print(dt_pdt)

# 2015-07-01 12:00:00-07:00

CAUTION: As of version 2.5.3, dateutil does not handle ambiguous datetimes correctly, and will
always default to

the later date. There is no way to construct an object with a dateutil timezone representing, for
example

2015-11-01 1:30 EDT-4, since this is during a daylight savings time transition.

All edge cases are handled properly when using pytz, but pytz time zones should not be directly
attached to time
zones through the constructor. Instead, a pytz time zone should be attached using the time zone's
localize

method:

from datetime import datetime, timedelta

import pytz

PT = pytz.timezone('US/Pacific')

dt_pst = PT.localize(datetime(2015, 1, 1, 12))

dt_pdt = PT.localize(datetime(2015, 11, 1, 0, 30))

print(dt_pst)

# 2015-01-01 12:00:00-08:00

print(dt_pdt)

# 2015-11-01 00:30:00-07:00

Be aware that if you perform datetime arithmetic on a pytz-aware time zone, you must either
perform the

calculations in UTC (if you want absolute elapsed time), or you must call normalize() on the result:

GoalKicker.com – Python® Notes for Professionals 44

dt_new = dt_pdt + timedelta(hours=3) # This should be 2:30 AM PST

print(dt_new)

# 2015-11-01 03:30:00-07:00

dt_corrected = PT.normalize(dt_new)

print(dt_corrected)

# 2015-11-01 02:30:00-08:00

Section 5.3: Computing time dierences

the timedelta module comes in handy to compute differences between times:

from datetime import datetime, timedelta

now = datetime.now()

then = datetime(2016, 5, 23) # datetime.datetime(2016, 05, 23, 0, 0, 0)

Specifying time is optional when creating a new datetime object

delta = now-then

delta is of type timedelta

print(delta.days)

# 60
print(delta.seconds)

# 40826

To get n day's after and n day's before date we could use:

n day's after date:

def get_n_days_after_date(date_format="%d %B %Y", add_days=120):

date_n_days_after = datetime.datetime.now() + timedelta(days=add_days)

return date_n_days_after.strftime(date_format)

n day's before date:

def get_n_days_before_date(self, date_format="%d %B %Y", days_before=120):

date_n_days_ago = datetime.datetime.now() - timedelta(days=days_before)

return date_n_days_ago.strftime(date_format)

Section 5.4: Basic datetime objects usage

The datetime module contains three primary types of objects - date, time, and datetime.

import datetime

# Date object

today = datetime.date.today()

new_year = datetime.date(2017, 01, 01) #datetime.date(2017, 1, 1)

# Time object

noon = datetime.time(12, 0, 0) #datetime.time(12, 0)

# Current datetime

now = datetime.datetime.now()

GoalKicker.com – Python® Notes for Professionals 45

# Datetime object

millenium_turn = datetime.datetime(2000, 1, 1, 0, 0, 0) #datetime.datetime(2000, 1, 1, 0, 0)

Arithmetic operations for these objects are only supported within same datatype and performing
simple arithmetic

with instances of different types will result in a TypeError.

# subtraction of noon from today

noon-today

Traceback (most recent call last):

File "<stdin>", line 1, in <module>


TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.date'

However, it is straightforward to convert between types.

# Do this instead

print('Time since the millenium at midnight: ',

datetime.datetime(today.year, today.month, today.day) - millenium_turn)

# Or this

print('Time since the millenium at noon: ',

datetime.datetime.combine(today, noon) - millenium_turn)

Section 5.5: Switching between time zones

To switch between time zones, you need datetime objects that are timezone-aware.

from datetime import datetime

from dateutil import tz

utc = tz.tzutc()

local = tz.tzlocal()

utc_now = datetime.utcnow()

utc_now # Not timezone-aware.

utc_now = utc_now.replace(tzinfo=utc)

utc_now # Timezone-aware.

local_now = utc_now.astimezone(local)

local_now # Converted to local time.

Section 5.6: Simple date arithmetic

Dates don't exist in isolation. It is common that you will need to find the amount of time between
dates or

determine what the date will be tomorrow. This can be accomplished using timedelta objects

import datetime

today = datetime.date.today()

print('Today:', today)

yesterday = today - datetime.timedelta(days=1)

print('Yesterday:', yesterday)

tomorrow = today + datetime.timedelta(days=1)

print('Tomorrow:', tomorrow)
print('Time between tomorrow and yesterday:', tomorrow - yesterday)

You might also like