Date and Time support

Overview

Overview

The datetime module supplies classes for manipulating dates and times in both simple and complex ways
A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects
For applications requiring aware objects, datetime and time objects have an optional time zone information attribute, tzinfo

class datetime.time

class datetime.time

Overview

A time object represents a (local) time of day, independent of any particular day
time object @python3 docs

class datetime.date

class datetime.date

Overview

A date object represents a date (year, month and day)
date object @python3 docs

class datetime.datetime

class datetime.datetime

Overview

A datetime object is a single object containing all the information from a date object and a time object.
datetime object @python3 docs

class datetime.timedelta

class datetime.timedelta

Overview

A timedelta object represents a duration, the difference between two dates or times.
timedelta object @python3 docs

class datetime.tzinfo

class datetime.tzinfo

Overview

An abstract base class. Capture information about the offset from UTC time, the time zone name, and whether Daylight Saving Time is in effect.
timedelta object @python3 docs

Extensions to the standard datetime module

Extensions to the standard datetime module

The dateutil module

dateutil module provides powerful extensions, good documentation and recent updates

Examples

Examples

Get current local and UTC datetimes


				import datetime

				# returns naive datetime object
				datetime_today = datetime.datetime.today()

				# equivalent to datetime.today(), when no tzinfo object is passed
				datetime_now = datetime.datetime.now()

				# returns the UTC time
				datetime_utc = datetime.datetime.utcnow()

				print(datetime_today)
				print(datetime_now)
				print(datetime_utc)

				#2018-04-18 18:04:11.148224
				#2018-04-18 18:04:11.148232
				#2018-04-18 15:04:11.148234
			

Get current date and time


				import datetime

				# get current date
				date_now = datetime.date.today()
				# or:
				# date_now = datetime.datetime.today().date()
				print("Current date: ",date_now)

				# get current time
				time_now = datetime.datetime.today().time()
				print("Current time: ",time_now)

				#Current date:  2018-04-18
				#Current time:  17:59:19.556068
			

Format datetime object as string

Check strftime() and strptime() Behavior, where are published all formatting codes supported by Python


				import datetime

				# get the date object
				today = datetime.datetime.today()

				# now, format it as string, using the format codes:
				print("Year:", today.strftime("%Y"))
				print("Month:", today.strftime("%m"))
				print("Day:", today.strftime("%d"))
				print("Hour:", today.strftime("%H"))
				print("Minutes:", today.strftime("%M"))
				print("Seconds:", today.strftime("%s"))
			

Create datetime object from string


				import datetime

				dt = datetime.datetime.strptime("15/02/17 22:10", "%d/%m/%y %H:%M")
				print(dt)
				# 2017-02-15 22:10:00

				bdate = datetime.datetime.strptime("18.12.31", "%y.%m.%d")
				print(bdate)
				# 2018-12-31 00:00:00
			

Calculate time interval


				from datetime import datetime

				t1 = datetime.strptime("08:30", "%H:%M")
				t2 = datetime.strptime("12:15", "%H:%M")
				print(t2 - t1)

				#3:45:00
			

Timing your code

For better precision (to account only the CPU time of your process ) use Python profilers built-in modules


				import time
				from functools import reduce

				#start timer
				start = time.time()

				# do some time intensive stuff:
				sum = reduce(lambda x,y:x+y, range(1,1_000_001))
				print("The sum of numbers from 1 to 1_000_000 is: ", sum)

				#end timer
				end = time.time()

				print("[Finished in {:.6f}s]".format(end - start))

				#The sum of numbers from 1 to 1_000_000 is:  500000500000
				#[Finished in 0.087371s]
			

Live Demos

Live Demos

Get weekday name for given date


			import datetime

			def get_weekday_name(date):
				named_wd = ["понеделник", "вторник", "сряда", "четвъртък", "петък", "събота", "неделя"]

				wd_name = named_wd[date.weekday()]
				return wd_name

			date = datetime.datetime.strptime("06/04/18", "%d/%m/%y")
			print( get_weekday_name(date) )
			#петък
		

When will my birthday be on Sunday?


			import datetime

			def get_next_sunday_date(bdate, period):
				"""get_next_sunday_date

				Args:
				    bdate (datetime): Object representing the date
				    period (tuple): (start_year,end_year) interval to look into

				Returns:
				    list: years, on which a date will be on Sunday
				"""
				years = []

				for y in range(*period):
					bdate_weekday = datetime.date(y, bdate.month, bdate.day).weekday()

					if bdate_weekday == 6:
						years.append(y)

				return years


			birth_date = datetime.datetime.strptime("31/12/00", "%d/%m/%y")

			sundays_years = get_next_sunday_date(birth_date, (2018,2100))
			print(sundays_years)
			#[2023, 2028, 2034, 2045, 2051, 2056, 2062, 2073, 2079, 2084, 2090]
		

Calculates the Western Easter date for given period

Using the Samuel Butcher Algorithm, published in Computus @ wikipedia.


			import datetime

			def butcher_easter(year):
			    "Returns Easter as a date object."
			    a = year % 19
			    b = year // 100
			    c = year % 100
			    d = (19 * a + b - b // 4 - ((b - (b + 8) // 25 + 1) // 3) + 15) % 30
			    e = (32 + 2 * (b % 4) + 2 * (c // 4) - d - (c % 4)) % 7
			    f = d + e - 7 * ((a + 11 * d + 22 * e) // 451) + 114
			    month = f // 31
			    day = f % 31 + 1
			    return datetime.date(year, month, day)

			def easter_dates_between(start, end):
			    for year in range(start, end+1):
			        print( butcher_easter(year).strftime("%d.%m.%Y") )


			easter_dates_between(2018, 2050)
		

The dateutil modules provides easter.py module, supporting Western, Ortodox and Julian Calendars.

Exercises

Days until my birthday

The Task

Write a function, that calculates the remaining days from current date to your next birthday day.
The output should be only the number of days.

Hint

To calculate difference between two date objects, t1 and t2, you can use: t1-t2 which will return a timedelta Object

Submission

PLease, prefix your filenames/archive with your name initials, before sending.
For instance: iep_task1.py or iep_tasks.rar
Send files to progressbg.python.course@gmail.com

These slides are based on

customised version of

Hakimel's reveal.js

framework