[go: up one dir, main page]

0% found this document useful (0 votes)
10 views6 pages

py 10

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

py 10

Uploaded by

fortiratra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

This will produce results similar to:

Today: 2016-04-15

Yesterday: 2016-04-14

Tomorrow: 2016-04-16

Difference between tomorrow and yesterday: 2 days, 0:00:00

Section 5.7: Converting timestamp to datetime

The datetime module can convert a POSIX timestamp to a ITC datetime object.

The Epoch is January 1st, 1970 midnight.

import time

from datetime import datetime

seconds_since_epoch=time.time() #1469182681.709

utc_date=datetime.utcfromtimestamp(seconds_since_epoch) #datetime.datetime(2016, 7, 22, 10,


18, 1,

709000)

Section 5.8: Subtracting months from a date accurately

Using the calendar module

import calendar

from datetime import date

def monthdelta(date, delta):

m, y = (date.month+delta) % 12, date.year + ((date.month)+delta-1) // 12

if not m: m = 12

d = min(date.day, calendar.monthrange(y, m)[1])

return date.replace(day=d,month=m, year=y)

next_month = monthdelta(date.today(), 1) #datetime.date(2016, 10, 23)

Using the dateutils module

import datetime

import dateutil.relativedelta

d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")

d2 = d - dateutil.relativedelta.relativedelta(months=1) #datetime.datetime(2013, 2, 28, 0, 0)

Section 5.9: Parsing an arbitrary ISO 8601 timestamp with

minimal libraries
Python has only limited support for parsing ISO 8601 timestamps. For strptime you need to know
exactly what

format it is in. As a complication the stringification of a datetime is an ISO 8601 timestamp, with
space as a

separator and 6 digit fraction:

str(datetime.datetime(2016, 7, 22, 9, 25, 59, 555555))

# '2016-07-22 09:25:59.555555'

but if the fraction is 0, no fractional part is output

GoalKicker.com – Python® Notes for Professionals 47

str(datetime.datetime(2016, 7, 22, 9, 25, 59, 0))

# '2016-07-22 09:25:59'

But these 2 forms need a different format for strptime. Furthermore, strptime' does not support at
all

parsing minute timezones that have a:in it, thus2016-07-22 09:25:59+0300can be parsed, but the

standard format2016-07-22 09:25:59+03:00` cannot.

There is a single-file library called iso8601 which properly parses ISO 8601 timestamps and only
them.

It supports fractions and timezones, and the T separator all with a single function:

import iso8601

iso8601.parse_date('2016-07-22 09:25:59')

# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)

iso8601.parse_date('2016-07-22 09:25:59+03:00')

# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<FixedOffset '+03:00' ...>)

iso8601.parse_date('2016-07-22 09:25:59Z')

# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)

iso8601.parse_date('2016-07-22T09:25:59.000111+03:00')

# datetime.datetime(2016, 7, 22, 9, 25, 59, 111, tzinfo=<FixedOffset '+03:00' ...>)

If no timezone is set, iso8601.parse_date defaults to UTC. The default zone can be changed with
default_zone

keyword argument. Notably, if this is None instead of the default, then those timestamps that do not
have an

explicit timezone are returned as naive datetimes instead:

iso8601.parse_date('2016-07-22T09:25:59', default_timezone=None)
# datetime.datetime(2016, 7, 22, 9, 25, 59)

iso8601.parse_date('2016-07-22T09:25:59Z', default_timezone=None)

# datetime.datetime(2016, 7, 22, 9, 25, 59, tzinfo=<iso8601.Utc>)

Section 5.10: Get an ISO 8601 timestamp

Without timezone, with microseconds

from datetime import datetime

datetime.now().isoformat()

# Out: '2016-07-31T23:08:20.886783'

With timezone, with microseconds

from datetime import datetime

from dateutil.tz import tzlocal

datetime.now(tzlocal()).isoformat()

# Out: '2016-07-31T23:09:43.535074-07:00'

With timezone, without microseconds

from datetime import datetime

from dateutil.tz import tzlocal

datetime.now(tzlocal()).replace(microsecond=0).isoformat()

# Out: '2016-07-31T23:10:30-07:00'

See ISO 8601 for more information about the ISO 8601 format.

Section 5.11: Parsing a string with a short time zone name into

GoalKicker.com – Python® Notes for Professionals 48

a timezone aware datetime object

Using the dateutil library as in the previous example on parsing timezone-aware timestamps, it is also
possible to

parse timestamps with a specified "short" time zone name.

For dates formatted with short time zone names or abbreviations, which are generally ambiguous
(e.g. CST, which

could be Central Standard Time, China Standard Time, Cuba Standard Time, etc - more can be found
here) or not

necessarily available in a standard database, it is necessary to specify a mapping between time zone
abbreviation

and tzinfo object.


from dateutil import tz

from dateutil.parser import parse

ET = tz.gettz('US/Eastern')

CT = tz.gettz('US/Central')

MT = tz.gettz('US/Mountain')

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

us_tzinfos = {'CST': CT, 'CDT': CT,

'EST': ET, 'EDT': ET,

'MST': MT, 'MDT': MT,

'PST': PT, 'PDT': PT}

dt_est = parse('2014-01-02 04:00:00 EST', tzinfos=us_tzinfos)

dt_pst = parse('2016-03-11 16:00:00 PST', tzinfos=us_tzinfos)

After running this:

dt_est

# datetime.datetime(2014, 1, 2, 4, 0, tzinfo=tzfile('/usr/share/zoneinfo/US/Eastern'))

dt_pst

# datetime.datetime(2016, 3, 11, 16, 0, tzinfo=tzfile('/usr/share/zoneinfo/US/Pacific'))

It is worth noting that if using a pytz time zone with this method, it will not be properly localized:

from dateutil.parser import parse

import pytz

EST = pytz.timezone('America/New_York')

dt = parse('2014-02-03 09:17:00 EST', tzinfos={'EST': EST})

This simply attaches the pytz time zone to the datetime:

dt.tzinfo # Will be in Local Mean Time!

# <DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD>

If using this method, you should probably re-localize the naive portion of the datetime after parsing:

dt_fixed = dt.tzinfo.localize(dt.replace(tzinfo=None))

dt_fixed.tzinfo # Now it's EST.

# <DstTzInfo 'America/New_York' EST-1 day, 19:00:00 STD>)

Section 5.12: Fuzzy datetime parsing (extracting datetime out

of a text)
It is possible to extract a date out of a text using the dateutil parser in a "fuzzy" mode, where
components of the

GoalKicker.com – Python® Notes for Professionals 49

string not recognized as being part of a date are ignored.

from dateutil.parser import parse

dt = parse("Today is January 1, 2047 at 8:21:00AM", fuzzy=True)

print(dt)

dt is now a datetime object and you would see datetime.datetime(2047, 1, 1, 8, 21) printed.

Section 5.13: Iterate over dates

Sometimes you want to iterate over a range of dates from a start date to some end date. You can do
it using

datetime library and timedelta object:

import datetime

# The size of each step in days

day_delta = datetime.timedelta(days=1)

start_date = datetime.date.today()

end_date = start_date + 7*day_delta

for i in range((end_date - start_date).days):

print(start_date + i*day_delta)

Which produces:

2016-07-21

2016-07-22

2016-07-23

2016-07-24

2016-07-25

2016-07-26

2016-07-27

GoalKicker.com – Python® Notes for Professionals 50

Chapter 6: Date Formatting

Section 6.1: Time between two date-times

from datetime import datetime

a = datetime(2016,10,06,0,0,0)
b = datetime(2016,10,01,23,59,59)

a-b

# datetime.timedelta(4, 1)

(a-b).days

#4

(a-b).total_seconds()

# 518399.0

Section 6.2: Outputting datetime object to string

Uses C standard format codes.

from datetime import datetime

datetime_for_string = datetime(2016,10,1,0,0)

datetime_string_format = '%b %d %Y, %H:%M:%S'

datetime.strftime(datetime_for_string,datetime_string_format)

# Oct 01 2016, 00:00:00

Section 6.3: Parsing string to datetime object

Uses C standard format codes.

from datetime import datetime

datetime_string = 'Oct 1 2016, 00:00:00'

datetime_string_format = '%b %d %Y, %H:%M:%S'

datetime.strptime(datetime_string, datetime

You might also like