1. Home
  2. Training Library
  3. DevOps
  4. Courses
  5. Introduction to Python for Programmers

Working With Dates and Times

Developed with
Trivera

Contents

keyboard_tab

The course is part of this learning path

Introduction to Python
course-steps 3 certification 1 lab-steps 3
play-arrow
Working With Dates and Times
Overview
DifficultyIntermediate
Duration55m
Students1250
Ratings
4.1/5
star star star star star-border

Description

In this first course, we introduce the Python Language, the declaration model, and how variables and functions are used in python.

Our learning objectives for this course are to introduce the python language and to be able to recognize and explain the core concepts of the Python language.

Transcript

- [Instructor] Hi, and welcome back! Let's look at dates and times. So our learning objectives for this lecture are to learn how to create date and time objects, making date and time calculations, getting Unix-style date stamps, formatting dates, parsing and working with calendars. Python provides several modules for working with dates and times. The standard library includes the datetime module, which provides the date, datetime, and time classes. These basic classes cover the most datetime-related needs. The time module in the standard library works with times, including dates, in either e-POP time, or time tuple format. The calender module has tools for generating calendars in text and HTML. If you need to parse dates from text or work with the time zones, the dateutil module, which is not in the standard library, but which is included with Anaconda, is very useful. The arrow module attempts to consolidate all datetime-related functionality into a single, easy-to-use module. Let's look at ways to store dates and times. There are three ways, at least, in which dates and times can be stored. The classes from the datetime module store time data as date, time, or datetime objects. Routines in the time module return a given datetime as a Unix e-POP time, which is the number of seconds since December 31st, 1969. For some functions return a nine-element tuple of year, month, day, hour, minute, second, weekday, days, since December 31st. The dateutil module uses the classes from datetime, as does arrow. 

Python provides the datetime module for manipulating dates and times. Once you have created date or time objects, you can combine them and extract the time units you need. The date object contains a valid year, month and day. The time object contains a valid hour, minute, second, and microsecond. The datetime object combines a date with a time. Timedelta presents the difference between the two preceding dates. If we look through our example code here, the first line gets today's date, then we get today's date and time, then a datetime object that has attributes for datetime paths. Number four, it creates a date object; line five, date objects can be subtracted from other date objects; and six shows shows the timedelta that has days, seconds, and microseconds. Seven lets us create a timedelta of 10 days, and number eight allows us to add timedelta to datetime. And here we create a datetime object. So how do we go about formatting dates and times? In our example script here, our first line creates the datetime object; and then second, we print using the default format; and third, we format giving us a output print. The range on three is really zero to 61, and this accounts for leap seconds and the very rare double leap second. If utcoffset returns timedelta and minutes=-30, %z is replaced with the string, -0330. 

Okay, so what if we wanna parse date or time strings? To parse dates from strings, use one of the strptime methods. Now there are two different versions which return different representations of the date and time. In both cases, you parse strptime, the time string, followed by a template that uses the same directives as strftime. Time.stprtime returns a time tuple. It is a named tuple, so to get the year, for instance, you can use either tuple zero, or tuple year datetime.strptime returns a new date object. So, for example, if we take our data as string, for the string we parse the template in, we take timetuple and we get the date string, parse the template, parse out of detail for ourselves. Okay, so that's kinda complex. There's an easier way to parse dates. The dateutil.parser module provides a parse function that will parse any date or datetime string, without the need to put together directives as with strptime. The parse function has several flags to deal with variations in date formats, such as European style day first. The value returned by parse is a normal Python datetime.datetime. So, for example, if we import dateutil and we take a date string; first of all, we list our assorted date strings, and then second, we parse with dateutil.parser.parse , which doesn't need a template. Okay, so what about converting time stamps? Certain functions such as os.gettime or os.getattime return a Unix-style date stamp. This is the number of seconds since January 1st, 1970, a point in time usually called the Unix epoch. You may also get this version of a date and time from other sources. To convert this to a useful format, use datetime.fromtimestamp to convert to a datetime object, or time.localtime to convert to a timetuple. The time.time method returns the current date and time as a time stamp. Converting to a time stamp takes two steps. First, get the date and time to a timetuple, and then call time.mktime. So first, we create a Python datetime object; second, we extract a timetuple and use it to make a Unix epoch time, getEpochTime for right now; and then we loop through the three epoch times. Now, note, Windows requires minimum values of 86400. Non-Windows platforms could use zero. We then convert the epoch time to timetuple, and then convert epoch time to Python datetime object. The time zones are fairly poorly supported in the standard library, so the datetime.datetime class has some UTC-based methods, but the dateutil module supports time zones out of the box. So in addition, it has features that can combine the most useful parts of a datetime and calendar packages. If you use dateutil to parse a datetime string that has a time zone, it will automatically add that to the date or datetime object. The time zone is usually specified as the offset from UTC. So EDT would be minus dour hours and PST would be minus eight hours. The calendar module provides two classes for generating calendars. The TextCalendar generates calendars as plain text, and the HTMLCalendar generates the calendars as HTML. Both support formatmonth and formatyear methods. TextCalendar, for convenience, also provides prmonth and pryear methods, which call print on the strings returned by formatmonth and formatyear . For year calendars, an option argument specifies the number of months per row. HTMLCalendar adds formatyear page, which returns an entire webpage, complete with headers and optional CSS file names. You can add optional parameters for the width of the day column and the number of lines for each week. The defaults are two for the day and one for the lines per week, so you can alter the output to change to suit whatever your page or document object model requires. So, in our example, we create a TextCalendar object, we format one month as text, then we create an HTMLCalendar object, and then we format one month as HTML.

About the Author

Students72738
Courses94
Learning paths45

Head of Content

Andrew is an AWS certified professional who is passionate about helping others learn how to use and gain benefit from AWS technologies. Andrew has worked for AWS and for AWS technology partners Ooyala and Adobe.  His favorite Amazon leadership principle is "Customer Obsession" as everything AWS starts with the customer. Passions around work are cycling and surfing, and having a laugh about the lessons learnt trying to launch two daughters and a few start ups. 

Covered Topics