Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping

Table of Contents

Recommended Course

A Beginner’s Guide to the Python time Module

Mastering Python's Built-in time Module

39m · 7 lessons

A Beginner’s Guide to the Python time Module

A Beginner’s Guide to the Python time Module

byAlex RonquilloReading time estimate 29mintermediatestdlib

Table of Contents

Remove ads

Recommended Course

Mastering Python's Built-in time Module(39m)

The Pythontime module provides many ways of representing time in code, such as objects,numbers, and strings. It also provides functionality other than representing time, like waiting during code execution and measuring the efficiency of your code.

This article will walk you through the most commonly used functions and objects intime.

By the end of this article, you’ll be able to:

  • Understand core concepts at the heart of working with dates and times, such as epochs, time zones, and daylight savings time
  • Represent time in code using floats, tuples, andstruct_time
  • Convert between different time representations
  • Suspend thread execution
  • Measure code performance usingperf_counter()

You’ll start by learning how you can use a floating point number to represent time.

Free Bonus:Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Dealing With Python Time Using Seconds

One of the ways you can manage the concept of Python time in your application is by using a floating point number that represents the number of seconds that have passed since the beginning of an era—that is, since a certain starting point.

Let’s dive deeper into what that means, why it’s useful, and how you can use it to implement logic, based on Python time, in your application.

The Epoch

You learned in the previous section that you can manage Python time with a floating point number representing elapsed time since the beginning of an era.

Merriam-Webster defines an era as:

  • A fixed point in time from which a series of years is reckoned
  • A system of chronological notation computed from a given date as basis

The important concept to grasp here is that, when dealing with Python time, you’re considering a period of time identified by a starting point. In computing, you call this starting point theepoch.

The epoch, then, is the starting point against which you can measure the passage of time.

For example, if you define the epoch to be midnight on January 1, 1970 UTC—the epoch as defined on Windows and most UNIX systems—then you can represent midnight on January 2, 1970 UTC as86400 seconds since the epoch.

This is because there are 60 seconds in a minute, 60 minutes in an hour, and 24 hours in a day. January 2, 1970 UTC is only one day after the epoch, so you can apply basic math to arrive at that result:

Python
>>>60*60*2486400

It is also important to note that you can still represent time before the epoch. The number of seconds would just be negative.

For example, you would represent midnight on December 31, 1969 UTC (using an epoch of January 1, 1970) as-86400 seconds.

While January 1, 1970 UTC is a common epoch, it is not the only epoch used in computing. In fact, different operating systems, filesystems, and APIs sometimes use different epochs.

As you saw before, UNIX systems define the epoch as January 1, 1970. The Win32 API, on the other hand, defines the epoch asJanuary 1, 1601.

You can usetime.gmtime() to determine your system’s epoch:

Python
>>>importtime>>>time.gmtime(0)time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

You’ll learn aboutgmtime() andstruct_time throughout the course of this article. For now, just know that you can usetime to discover the epoch using this function.

Now that you understand more about how to measure time in seconds using an epoch, let’s take a look at Python’stime module to see what functions it offers that help you do so.

Python Time in Seconds as a Floating Point Number

First,time.time() returns the number of seconds that have passed since the epoch. The return value is a floating point number to account for fractional seconds:

Python
>>>fromtimeimporttime>>>time()1551143536.9323719

The number you get on your machine may be very different because the reference point considered to be the epoch may be very different.

Further Reading: Python 3.7 introducedtime_ns(), which returns an integer value representing the same elapsed time since the epoch, but in nanoseconds rather than seconds.

Measuring time in seconds is useful for a number of reasons:

  • You can use a float to calculate the difference between two points in time.
  • A float is easilyserializable, meaning that it can be stored for data transfer and come out intact on the other side.

Sometimes, however, you may want to see thecurrent time represented as a string. To do so, you can pass the number of seconds you get fromtime() intotime.ctime().

Python Time in Seconds as a String Representing Local Time

As you saw before, you may want to convert the Python time, represented as the number of elapsed seconds since the epoch, to astring. You can do so usingctime():

Python
>>>fromtimeimporttime,ctime>>>t=time()>>>ctime(t)'Mon Feb 25 19:11:59 2019'

Here, you’ve recorded the current time in seconds into thevariablet, then passedt as an argument toctime(), which returns a string representation of that same time.

Technical Detail: The argument, representing seconds since the epoch, is optional according to thectime() definition. If you don’t pass an argument, thenctime() uses the return value oftime() by default. So, you could simplify the example above:

Python
>>>fromtimeimportctime>>>ctime()'Mon Feb 25 19:11:59 2019'

The string representation of time, also known as atimestamp, returned byctime() is formatted with the following structure:

  1. Day of the week:Mon (Monday)
  2. Month of the year:Feb (February)
  3. Day of the month:25
  4. Hours, minutes, and seconds using the24-hour clock notation:19:11:59
  5. Year:2019

The previous example displays the timestamp of a particular moment captured from a computer in the South Central region of the United States. But, let’s say you live in Sydney, Australia, and you executed the same command at the same instant.

Instead of the above output, you’d see the following:

Python
>>>fromtimeimporttime,ctime>>>t=time()>>>ctime(t)'Tue Feb 26 12:11:59 2019'

Notice that theday of week,day of month, andhour portions of the timestamp are different than the first example.

These outputs are different because the timestamp returned byctime() depends on your geographical location.

Note: While the concept of time zones is relative to your physical location, you can modify this in your computer’s settings without actually relocating.

The representation of time dependent on your physical location is calledlocal time and makes use of a concept calledtime zones.

Note: Since local time is related to your locale, timestamps often account for locale-specific details such as the order of the elements in the string and translations of the day and month abbreviations.ctime() ignores these details.

Let’s dig a little deeper into the notion of time zones so that you can better understand Python time representations.

Understanding Time Zones

A time zone is a region of the world that conforms to a standardized time. Time zones are defined by their offset fromCoordinated Universal Time (UTC) and, potentially, the inclusion of daylight savings time (which we’ll cover in more detail later in this article).

Fun Fact: If you’re a native English speaker, you might be wondering why the abbreviation for “Coordinated Universal Time” is UTC rather than the more obvious CUT. However, if you’re a native French speaker, you would call it “Temps Universel Coordonné,” which suggests a different abbreviation: TUC.

Ultimately, theInternational Telecommunication Union and the International Astronomical Union compromised on UTC as the official abbreviation so that, regardless of language, the abbreviation would be the same.

UTC and Time Zones

UTC is the time standard against which all the world’s timekeeping is synchronized (or coordinated). It is not, itself, a time zone but rather a transcendent standard that defines what time zones are.

UTC time is precisely measured usingastronomical time, referring to the Earth’s rotation, andatomic clocks.

Time zones are then defined by their offset from UTC. For example, in North and South America, the Central Time Zone (CT) is behind UTC by five or six hours and, therefore, uses the notation UTC-5:00 or UTC-6:00.

Sydney, Australia, on the other hand, belongs to the Australian Eastern Time Zone (AET), which is ten or eleven hours ahead of UTC (UTC+10:00 or UTC+11:00).

This difference (UTC-6:00 to UTC+10:00) is the reason for the variance you observed in the two outputs fromctime() in the previous examples:

  • Central Time (CT):'Mon Feb 25 19:11:59 2019'
  • Australian Eastern Time (AET):'Tue Feb 26 12:11:59 2019'

These times are exactly sixteen hours apart, which is consistent with the time zone offsets mentioned above.

You may be wondering why CT can be either five or six hours behind UTC or why AET can be ten or eleven hours ahead. The reason for this is that some areas around the world, including parts of these time zones, observe daylight savings time.

Daylight Savings Time

Summer months generally experience moredaylight hours than winter months. Because of this, some areas observe daylight savings time (DST) during the spring and summer to make better use of those daylight hours.

For places that observe DST, their clocks will jump ahead one hour at the beginning of spring (effectively losing an hour). Then, in the fall, the clocks will be reset to standard time.

The letters S and D represent standard time and daylight savings time in time zone notation:

  • Central Standard Time (CST)
  • Australian Eastern Daylight Time (AEDT)

When you represent times as timestamps in local time, it is always important to consider whether DST is applicable or not.

ctime() accounts for daylight savings time. So, the output difference listed previously would be more accurate as the following:

  • Central Standard Time (CST):'Mon Feb 25 19:11:59 2019'
  • Australian Eastern Daylight Time (AEDT):'Tue Feb 26 12:11:59 2019'

Dealing With Python Time Using Data Structures

Now that you have a firm grasp on many fundamental concepts of time including epochs, time zones, and UTC, let’s take a look at more ways to represent time using the Pythontime module.

Python Time as a Tuple

Instead of using a number to represent Python time, you can use another primitive data structure: atuple.

The tuple allows you to manage time a little more easily by abstracting some of the data and making it more readable.

When you represent time as a tuple, each element in your tuple corresponds to a specific element of time:

  1. Year
  2. Month as an integer, ranging between 1 (January) and 12 (December)
  3. Day of the month
  4. Hour as an integer, ranging between 0 (12 A.M.) and 23 (11 P.M.)
  5. Minute
  6. Second
  7. Day of the week as an integer, ranging between 0 (Monday) and 6 (Sunday)
  8. Day of the year
  9. Daylight savings time as an integer with the following values:
    • 1 is daylight savings time.
    • 0 is standard time.
    • -1 is unknown.

Using the methods you’ve already learned, you can represent the same Python time in two different ways:

Python
>>>fromtimeimporttime,ctime>>>t=time()>>>t1551186415.360564>>>ctime(t)'Tue Feb 26 07:06:55 2019'>>>time_tuple=(2019,2,26,7,6,55,1,57,0)

In this case, botht andtime_tuple represent the same time, but the tuple provides a more readable interface for working with time components.

Technical Detail: Actually, if you look at the Python time represented bytime_tuple in seconds (which you’ll see how to do later in this article), you’ll see that it resolves to1551186415.0 rather than1551186415.360564.

This is because the tuple doesn’t have a way to represent fractional seconds.

While the tuple provides a more manageable interface for working with Python time, there is an even better object:struct_time.

Python Time as an Object

The problem with the tuple construct is that it still looks like a bunch of numbers, even though it’s better organized than a single, seconds-based number.

struct_time provides a solution to this by utilizingNamedTuple, from Python’scollections module, to associate the tuple’s sequence of numbers with useful identifiers:

Python
>>>fromtimeimportstruct_time>>>time_tuple=(2019,2,26,7,6,55,1,57,0)>>>time_obj=struct_time(time_tuple)>>>time_objtime.struct_time(tm_year=2019, tm_mon=2, tm_mday=26, tm_hour=7, tm_min=6, tm_sec=55, tm_wday=1, tm_yday=57, tm_isdst=0)

Technical Detail: If you’re coming from another language, the termsstruct andobject might be in opposition to one another.

In Python, there is nodata type calledstruct. Instead, everything is an object.

However, the namestruct_time is derived from theC-based time library where the data type is actually astruct.

In fact, Python’stime module, which isimplemented in C, uses thisstruct directly by including the header filetimes.h.

Now, you can access specific elements oftime_obj using the attribute’s name rather than an index:

Python
>>>day_of_year=time_obj.tm_yday>>>day_of_year57>>>day_of_month=time_obj.tm_mday>>>day_of_month26

Beyond the readability and usability ofstruct_time, it is also important to know because it is the return type of many of the functions in the Pythontime module.

Converting Python Time in Seconds to an Object

Now that you’ve seen the three primary ways of working with Python time, you’ll learn how to convert between the different time data types.

Converting between time data types is dependent on whether the time is in UTC or local time.

Coordinated Universal Time (UTC)

The epoch uses UTC for its definition rather than a time zone. Therefore, the seconds elapsed since the epoch is not variable depending on your geographical location.

However, the same cannot be said ofstruct_time. The object representation of Python time may or may not take your time zone into account.

There are two ways to convert a float representing seconds to astruct_time:

  1. UTC
  2. Local time

To convert a Python time float to a UTC-basedstruct_time, the Pythontime module provides a function calledgmtime().

You’ve seengmtime() used once before in this article:

Python
>>>importtime>>>time.gmtime(0)time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

You used this call to discover your system’s epoch. Now, you have a better foundation for understanding what’s actually happening here.

gmtime() converts the number of elapsed seconds since the epoch to astruct_time in UTC. In this case, you’ve passed0 as the number of seconds, meaning you’re trying to find the epoch, itself, in UTC.

Note: Notice the attributetm_isdst is set to0. This attribute represents whether the time zone is using daylight savings time. UTC never subscribes to DST, so that flag will always be0 when usinggmtime().

As you saw before,struct_time cannot represent fractional seconds, sogmtime() ignores the fractional seconds in the argument:

Python
>>>importtime>>>time.gmtime(1.99)time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=1, tm_wday=3, tm_yday=1, tm_isdst=0)

Notice that even though the number of seconds you passed was very close to2, the.99 fractional seconds were simply ignored, as shown bytm_sec=1.

Thesecs parameter forgmtime() is optional, meaning you can callgmtime() with no arguments. Doing so will provide the current time in UTC:

Python
>>>importtime>>>time.gmtime()time.struct_time(tm_year=2019, tm_mon=2, tm_mday=28, tm_hour=12, tm_min=57, tm_sec=24, tm_wday=3, tm_yday=59, tm_isdst=0)

Interestingly, there is no inverse for this function withintime. Instead, you’ll have to look in Python’scalendar module for a function namedtimegm():

Python
>>>importcalendar>>>importtime>>>time.gmtime()time.struct_time(tm_year=2019, tm_mon=2, tm_mday=28, tm_hour=13, tm_min=23, tm_sec=12, tm_wday=3, tm_yday=59, tm_isdst=0)>>>calendar.timegm(time.gmtime())1551360204

timegm() takes a tuple (orstruct_time, since it is a subclass of tuple) and returns the corresponding number of seconds since the epoch.

Historical Context: If you’re interested in whytimegm() is not intime, you can view the discussion inPython Issue 6280.

In short, it was originally added tocalendar becausetime closely follows C’s time library (defined intime.h), which contains no matching function. The above-mentioned issue proposed the idea of moving or copyingtimegm() intotime.

However, with advances to thedatetime library, inconsistencies in the patched implementation oftime.timegm(), and a question of how to then handlecalendar.timegm(), the maintainers declined the patch, encouraging the use ofdatetime instead.

Working with UTC is valuable in programming because it’s a standard. You don’t have to worry about DST, time zone, or locale information.

That said, there are plenty of cases when you’d want to use local time. Next, you’ll see how to convert from seconds to local time so that you can do just that.

Local Time

In your application, you may need to work with local time rather than UTC. Python’stime module provides a function for getting local time from the number of seconds elapsed since the epoch calledlocaltime().

The signature oflocaltime() is similar togmtime() in that it takes an optionalsecs argument, which it uses to build astruct_time using your local time zone:

Python
>>>importtime>>>time.time()1551448206.86196>>>time.localtime(1551448206.86196)time.struct_time(tm_year=2019, tm_mon=3, tm_mday=1, tm_hour=7, tm_min=50, tm_sec=6, tm_wday=4, tm_yday=60, tm_isdst=0)

Notice thattm_isdst=0. Since DST matters with local time,tm_isdst will change between0 and1 depending on whether or not DST is applicable for the given time. Sincetm_isdst=0, DST is not applicable for March 1, 2019.

In the United States in 2019, daylight savings time begins on March 10. So, to test if the DST flag will change correctly, you need to add 9 days’ worth of seconds to thesecs argument.

To compute this, you take the number of seconds in a day (86,400) and multiply that by 9 days:

Python
>>>new_secs=1551448206.86196+(86400*9)>>>time.localtime(new_secs)time.struct_time(tm_year=2019, tm_mon=3, tm_mday=10, tm_hour=8, tm_min=50, tm_sec=6, tm_wday=6, tm_yday=69, tm_isdst=1)

Now, you’ll see that thestruct_time shows the date to be March 10, 2019 withtm_isdst=1. Also, notice thattm_hour has also jumped ahead, to8 instead of7 in the previous example, because of daylight savings time.

Since Python 3.3,struct_time has also included two attributes that are useful in determining the time zone of thestruct_time:

  1. tm_zone
  2. tm_gmtoff

At first, these attributes were platform dependent, but they have been available on all platforms since Python 3.6.

First,tm_zone stores the local time zone:

Python
>>>importtime>>>current_local=time.localtime()>>>current_local.tm_zone'CST'

Here, you can see thatlocaltime() returns astruct_time with the time zone set toCST (Central Standard Time).

As you saw before, you can also tell the time zone based on two pieces of information, the UTC offset and DST (if applicable):

Python
>>>importtime>>>current_local=time.localtime()>>>current_local.tm_gmtoff-21600>>>current_local.tm_isdst0

In this case, you can see thatcurrent_local is21600 seconds behind GMT, which stands for Greenwich Mean Time. GMT is the time zone with no UTC offset: UTC±00:00.

21600 seconds divided by seconds per hour (3,600) means thatcurrent_local time isGMT-06:00 (orUTC-06:00).

You can use the GMT offset plus the DST status to deduce thatcurrent_local isUTC-06:00 at standard time, which corresponds to the Central standard time zone.

Likegmtime(), you can ignore thesecs argument when callinglocaltime(), and it will return the current local time in astruct_time:

Python
>>>importtime>>>time.localtime()time.struct_time(tm_year=2019, tm_mon=3, tm_mday=1, tm_hour=8, tm_min=34, tm_sec=28, tm_wday=4, tm_yday=60, tm_isdst=0)

Unlikegmtime(), the inverse function oflocaltime() does exist in the Pythontime module. Let’s take a look at how that works.

Converting a Local Time Object to Seconds

You’ve already seen how to convert a UTC time object to seconds usingcalendar.timegm(). To convert local time to seconds, you’ll usemktime().

mktime() requires you to pass a parameter calledt that takes the form of either a normal 9-tuple or astruct_time object representing local time:

Python
>>>importtime>>>time_tuple=(2019,3,10,8,50,6,6,69,1)>>>time.mktime(time_tuple)1552225806.0>>>time_struct=time.struct_time(time_tuple)>>>time.mktime(time_struct)1552225806.0

It’s important to keep in mind thatt must be a tuple representing local time, not UTC:

Python
>>>fromtimeimportgmtime,mktime>>># 1>>>current_utc=time.gmtime()>>>current_utctime.struct_time(tm_year=2019, tm_mon=3, tm_mday=1, tm_hour=14, tm_min=51, tm_sec=19, tm_wday=4, tm_yday=60, tm_isdst=0)>>># 2>>>current_utc_secs=mktime(current_utc)>>>current_utc_secs1551473479.0>>># 3>>>time.gmtime(current_utc_secs)time.struct_time(tm_year=2019, tm_mon=3, tm_mday=1, tm_hour=20, tm_min=51, tm_sec=19, tm_wday=4, tm_yday=60, tm_isdst=0)

Note: For this example, assume that the local time isMarch 1, 2019 08:51:19 CST.

This example shows why it’s important to usemktime() with local time, rather than UTC:

  1. gmtime() with no argument returns astruct_time using UTC.current_utc showsMarch 1, 2019 14:51:19 UTC. This is accurate becauseCST is UTC-06:00, so UTC should be 6 hours ahead of local time.

  2. mktime() tries to return the number of seconds, expecting local time, but you passedcurrent_utc instead. So, instead of understanding thatcurrent_utc is UTC time, it assumes you meantMarch 1, 2019 14:51:19 CST.

  3. gmtime() is then used to convert those seconds back into UTC, which results in an inconsistency. The time is nowMarch 1, 2019 20:51:19 UTC. The reason for this discrepancy is the fact thatmktime() expected local time. So, the conversion back to UTC addsanother 6 hours to local time.

Working with time zones is notoriously difficult, so it’s important to set yourself up for success by understanding the differences between UTC and local time and the Python time functions that deal with each.

Converting a Python Time Object to a String

While working with tuples is fun and all, sometimes it’s best to work with strings.

String representations of time, also known as timestamps, help make times more readable and can be especially useful for building intuitive user interfaces.

There are two Pythontime functions that you use for converting atime.struct_time object to a string:

  1. asctime()
  2. strftime()

You’ll begin by learning aboutasctime().

asctime()

You useasctime() for converting a time tuple orstruct_time to a timestamp:

Python
>>>importtime>>>time.asctime(time.gmtime())'Fri Mar  1 18:42:08 2019'>>>time.asctime(time.localtime())'Fri Mar  1 12:42:15 2019'

Bothgmtime() andlocaltime() returnstruct_time instances, for UTC and local time respectively.

You can useasctime() to convert eitherstruct_time to a timestamp.asctime() works similarly toctime(), which you learned about earlier in this article, except instead of passing a floating point number, you pass a tuple. Even the timestamp format is the same between the two functions.

As withctime(), the parameter forasctime() is optional. If you do not pass a time object toasctime(), then it will use the current local time:

Python
>>>importtime>>>time.asctime()'Fri Mar  1 12:56:07 2019'

As withctime(), it also ignores locale information.

One of the biggest drawbacks ofasctime() is its format inflexibility.strftime() solves this problem by allowing you to format your timestamps.

strftime()

You may find yourself in a position where the string format fromctime() andasctime() isn’t satisfactory for your application. Instead, you may want to format your strings in a way that’s more meaningful to your users.

One example of this is if you would like to display your time in a string that takes locale information into account.

To format strings, given astruct_time or Python time tuple, you usestrftime(), which stands for “stringformat time.”

strftime() takes two arguments:

  1. format specifies the order and form of the time elements in your string.
  2. t is an optional time tuple.

To format a string, you usedirectives. Directives are character sequences that begin with a% that specify a particular time element, such as:

  • %d: Day of the month
  • %m: Month of the year
  • %Y: Year

For example, you can output the date in your local time using theISO 8601 standard like this:

Python
>>>importtime>>>time.strftime('%Y-%m-%d',time.localtime())'2019-03-01'

Further Reading: While representing dates using Python time is completely valid and acceptable, you should also consider using Python’sdatetime module, which provides shortcuts and a more robust framework for working with dates and times together.

For example, you can simplify outputting a date in the ISO 8601 format usingdatetime:

Python
>>>fromdatetimeimportdate>>>date(year=2019,month=3,day=1).isoformat()'2019-03-01'

To learn more about using the Pythondatetime module, check outUsing Python datetime to Work With Dates and Times

As you saw before, a great benefit of usingstrftime() overasctime() is its ability to render timestamps that make use of locale-specific information.

For example, if you want to represent the date and time in a locale-sensitive way, you can’t useasctime():

Python
>>>fromtimeimportasctime>>>asctime()'Sat Mar  2 15:21:14 2019'>>>importlocale>>>locale.setlocale(locale.LC_TIME,'zh_HK')# Chinese - Hong Kong'zh_HK'>>>asctime()'Sat Mar  2 15:58:49 2019'

Notice that even after programmatically changing your locale,asctime() still returns the date and time in the same format as before.

Technical Detail:LC_TIME is the locale category for date and time formatting. Thelocale argument'zh_HK' may be different, depending on your system.

When you usestrftime(), however, you’ll see that it accounts for locale:

Python
>>>fromtimeimportstrftime,localtime>>>strftime('%c',localtime())'Sat Mar  2 15:23:20 2019'>>>importlocale>>>locale.setlocale(locale.LC_TIME,'zh_HK')# Chinese - Hong Kong'zh_HK'>>>strftime('%c',localtime())'六  3/ 2 15:58:12 2019' 2019'

Here, you have successfully utilized the locale information because you usedstrftime().

Note:%c is the directive for locale-appropriate date and time.

If the time tuple is not passed to the parametert, thenstrftime() will use the result oflocaltime() by default. So, you could simplify the examples above by removing the optional second argument:

Python
>>>fromtimeimportstrftime>>>strftime('The current local datetime is:%c')'The current local datetime is: Fri Mar  1 23:18:32 2019'

Here, you’ve used the default time instead of passing your own as an argument. Also, notice that theformat argument can consist of text other than formatting directives.

Further Reading: Check out this thoroughlist of directives available tostrftime().

The Pythontime module also includes the inverse operation of converting a timestamp back into astruct_time object.

Converting a Python Time String to an Object

When you’re working with date and time related strings, it can be very valuable to convert the timestamp to a time object.

To convert a time string to astruct_time, you usestrptime(), which stands for “stringparse time”:

Python
>>>fromtimeimportstrptime>>>strptime('2019-03-01','%Y-%m-%d')time.struct_time(tm_year=2019, tm_mon=3, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=60, tm_isdst=-1)

The first argument tostrptime() must be the timestamp you wish to convert. The second argument is theformat that the timestamp is in.

Theformat parameter is optional and defaults to'%a %b %d %H:%M:%S %Y'. Therefore, if you have a timestamp in that format, you don’t need to pass it as an argument:

Python
>>>strptime('Fri Mar 01 23:38:40 2019')time.struct_time(tm_year=2019, tm_mon=3, tm_mday=1, tm_hour=23, tm_min=38, tm_sec=40, tm_wday=4, tm_yday=60, tm_isdst=-1)

Since astruct_time has 9 key date and time components,strptime() must provide reasonable defaults for values for those components it can’t parse fromstring.

In the previous examples,tm_isdst=-1. This means thatstrptime() can’t determine by the timestamp whether it represents daylight savings time or not.

Now you know how to work with Python times and dates using thetime module in a variety of ways. However, there are other uses fortime outside of simply creating time objects, getting Python time strings, and using seconds elapsed since the epoch.

Suspending Execution

One really useful Python time function issleep(), which suspends the thread’s execution for a specified amount of time.

For example, you can suspend your program’s execution for 10 seconds like this:

Python
>>>fromtimeimportsleep,strftime>>>strftime('%c')'Fri Mar  1 23:49:26 2019'>>>sleep(10)>>>strftime('%c')'Fri Mar  1 23:49:36 2019'

Your program willprint the first formatteddatetime string, then pause for 10 seconds, and finally print the second formatteddatetime string.

You can also pass fractional seconds tosleep():

Python
>>>fromtimeimportsleep>>>sleep(0.5)

sleep() is useful for testing or making your program wait for any reason, but you must be careful not to halt your production code unless you have good reason to do so.

Before Python 3.5, a signal sent to your process could interruptsleep(). However, in 3.5 and later,sleep() will always suspend execution for at least the amount of specified time, even if the process receives a signal.

sleep() is just one Python time function that can help you test your programs and make them more robust.

Measuring Performance

You canusetime to measure the performance of your program.

The way you do this is to useperf_counter() which, as the name suggests, provides a performance counter with a high resolution to measure short distances of time.

To useperf_counter(), you place a counter before your code begins execution as well as after your code’s execution completes:

Python
>>>fromtimeimportperf_counter>>>deflongrunning_function():...foriinrange(1,11):...time.sleep(i/i**2)...>>>start=perf_counter()>>>longrunning_function()>>>end=perf_counter()>>>execution_time=(end-start)>>>execution_time8.201258441999926

First,start captures the moment before you call the function.end captures the moment after the function returns. The function’s total execution time took(end - start) seconds.

Technical Detail: Python 3.7 introducedperf_counter_ns(), which works the same asperf_counter(), but uses nanoseconds instead of seconds.

perf_counter() (orperf_counter_ns()) is the most precise way to measure the performance of your code using one execution. However, if you’re trying to accurately gauge the performance of a code snippet, I recommend using thePythontimeit module.

timeit specializes in running code many times to get a more accurate performance analysis and helps you to avoid oversimplifying your time measurement as well as other common pitfalls.

Conclusion

Congratulations! You now have a great foundation for working with dates and times in Python.

Now, you’re able to:

  • Use a floating point number, representing seconds elapsed since the epoch, to deal with time
  • Manage time using tuples andstruct_time objects
  • Convert between seconds, tuples, and timestamp strings
  • Suspend the execution of a Python thread
  • Measure performance usingperf_counter()

On top of all that, you’ve learned some fundamental concepts surrounding date and time, such as:

  • Epochs
  • UTC
  • Time zones
  • Daylight savings time

Now, it’s time for you to apply your newfound knowledge of Python time in your real world applications!

Further Reading

If you want to continue learning more about using dates and times in Python, take a look at the following modules:

  • datetime: A more robust date and time module in Python’s standard library
  • timeit: A module for measuring the performance of code snippets
  • astropy: Higher precision datetimes used in astronomy

Recommended Course

Mastering Python's Built-in time Module(39m)

🐍 Python Tricks 💌

Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

AboutAlex Ronquillo

Alex Ronquillo is a Software Engineer at thelab. He’s an avid Pythonista who is also passionate about writing and game development.

» More about Alex

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.


Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics:intermediatestdlib

Related Learning Paths:

Related Courses:

Related Tutorials:

Keep reading Real Python by creating a free account or signing in:

Already have an account?Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Get the Python Cheat Sheet (Free PDF)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2026 Movatter.jp