Python3 Date and Time
Python programs can handle dates and times in many ways, and converting date formats is a common function.
Python provides a time and calendar module that can be used to format dates and times.
Time intervals are floating-point decimals in seconds.
Each timestamp is represented by how much time has passed since midnight on January 1, 1970 (the epoch).
Python’s time module has many functions that can convert common date formats. For example, the function time.time() is used to get the current timestamp, as shown in the following example:
Example
Section titled “Example”Output of the above example:
Timestamp units are best suited for date arithmetic. However, dates before 1970 cannot be represented this way. Dates too far in the future also won’t work; UNIX and Windows only support up to 2038.
What is a Time Tuple?
Section titled “What is a Time Tuple?”Many Python functions process time using a tuple of 9 numbers:
| Index | Field | Value |
| 0 | 4-digit year | 2008 |
| 1 | Month | 1 to 12 |
| 2 | Day | 1 to 31 |
| 3 | Hour | 0 to 23 |
| 4 | Minute | 0 to 59 |
| 5 | Second | 0 to 61 (60 or 61 are leap seconds) |
| 6 | Day of week | 0 to 6 (0 is Monday) |
| 7 | Day of year | 1 to 366 (Julian calendar) |
| 8 | DST | -1, 0, 1, -1 is the flag for determining whether DST is in effect |
The above is the struct_time tuple. This structure has the following attributes:
| Index | Attribute | Value |
| 0 | tm_year | 2008 |
| 1 | tm_mon | 1 to 12 |
| 2 | tm_mday | 1 to 31 |
| 3 | tm_hour | 0 to 23 |
| 4 | tm_min | 0 to 59 |
| 5 | tm_sec | 0 to 61 (60 or 61 are leap seconds) |
| 6 | tm_wday | 0 to 6 (0 is Monday) |
| 7 | tm_yday | Day of the year, 1 to 366 |
| 8 | tm_isdst | Whether DST is in effect. Values: 1 (DST), 0 (not DST), -1 (unknown), default -1 |
Getting the Current Time
Section titled “Getting the Current Time”To convert from a timestamp returning a floating-point number to a time tuple, simply pass the floating-point number to a function like localtime.
Output of the above example:
Getting Formatted Time
Section titled “Getting Formatted Time”You can choose various formats according to your needs, but the simplest function to get a readable time pattern is asctime():
Output of the above example:
Formatting Dates
Section titled “Formatting Dates”We can use the strftime method of the time module to format dates:
Example
Section titled “Example”Output of the above example:
Date and time formatting symbols in Python:
- %y Two-digit year representation (00-99)
- %Y Four-digit year representation (000-9999)
- %m Month (01-12)
- %d Day of the month (0-31)
- %H 24-hour format hours (0-23)
- %I 12-hour format hours (01-12)
- %M Minutes (00-59)
- %S Seconds (00-59)
- %a Locale’s abbreviated weekday name
- %A Locale’s full weekday name
- %b Locale’s abbreviated month name
- %B Locale’s full month name
- %c Locale’s appropriate date and time representation
- %j Day of the year (001-366)
- %p Locale’s equivalent of AM or PM
- %U Week number of the year (00-53) Sunday as the first day of the week
- %w Weekday (0-6), Sunday as the first day of the week
- %W Week number of the year (00-53) Monday as the first day of the week
- %x Locale’s appropriate date representation
- %X Locale’s appropriate time representation
- %Z Name of the current time zone
- %% % sign itself
Getting a Month’s Calendar
Section titled “Getting a Month’s Calendar”The Calendar module has a wide range of methods for handling yearly and monthly calendars, such as printing a month’s calendar:
Example
Section titled “Example”Output of the above example:
Time Module
Section titled “Time Module”The Time module contains the following built-in functions, both for time processing and for converting time formats:
| No. | Function & Description | Example |
|---|---|---|
| 1 | time.altzone Returns the offset of the local DST timezone, in seconds west of UTC. If the local DST timezone is east of UTC, it returns a negative value (e.g., Western Europe, including the UK). Only usable if DST is enabled in the region. |
The following example shows how to use the altzone() function: |
| 2 | time.asctime([tupletime]) Accepts a time tuple and returns a readable 24-character string in the form "Tue Dec 11 18:07:14 2008" (Tuesday, December 11, 2008, 18:07:14). |
The following example shows how to use the asctime() function: |
| 3 | time.clock() Returns the current CPU time as a floating-point number of seconds. Used to measure the time consumption of different programs, more useful than time.time(). |
Since this method depends on the operating system, it was deprecated in Python 3.3 and removed in version 3.8. The following two functions should be used instead. |
| 4 | time.ctime([secs]) Equivalent to asctime(localtime(secs)). Without arguments, equivalent to asctime(). |
The following example shows how to use the ctime() function: |
| 5 | time.gmtime([secs]) Receives a timestamp (floating-point seconds elapsed since the epoch 1970) and returns the time tuple t in Greenwich Mean Time. Note: t.tm_isdst is always 0. |
The following example shows how to use the gmtime() function: |
| 6 | time.localtime([secs]) Receives a timestamp (floating-point seconds elapsed since the epoch 1970) and returns the time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether local DST is in effect at that time). |
The following example shows how to use the localtime() function: |
| 7 | time.mktime(tupletime) Accepts a time tuple and returns a timestamp (floating-point seconds elapsed since the epoch 1970). |
Example |
| 8 | time.sleep(secs) Suspends the calling thread's execution. secs refers to the number of seconds. |
The following example shows how to use the sleep() function: |
| 9 | time.strftime(fmt[,tupletime]) Receives a time tuple and returns a readable string representing the local time, with the format determined by fmt. |
The following example shows how to use the strftime() function: |
| 10 | time.strptime(str,fmt='%a %b %d %H:%M:%S %Y') Parses a time string into a time tuple according to the format fmt. |
The following example shows how to use the strptime() function: |
| 11 | time.time( ) Returns the current timestamp (floating-point seconds elapsed since the epoch 1970). |
The following example shows how to use the time() function: |
| 12 | time.tzset() Reinitializes time-related settings based on the environment variable TZ. |
Example |
| 13 | time.perf_counter() Returns the precise time of the timer (system runtime), including sleep time across the entire system. Since the reference point of the return value is undefined, only the difference between consecutive call results is valid. |
Example |
| 14 | time.process_time() Returns the total CPU time consumed by the current process, excluding sleep time. Since the reference point of the return value is undefined, only the difference between consecutive call results is valid. |
The Time module contains the following two very important attributes:
| No. | Attribute & Description |
|---|---|
| 1 | time.timezone The attribute time.timezone is the offset in seconds of the local timezone (without DST) from UTC (>0 for the Americas; <=0 for most of Europe, Asia, Africa). |
| 2 | time.tzname The attribute time.tzname contains a pair of strings that vary depending on the situation: the name of the local timezone with DST and without DST. |
Calendar Module
Section titled “Calendar Module”The functions in this module are all calendar-related, such as printing a character-based monthly calendar for a given month.
Monday is the default first day of the week, and Sunday is the default last day. To change the settings, call the calendar.setfirstweekday() function. The module contains the following built-in functions:
| No. | Function & Description |
|---|---|
| 1 | calendar.calendar(year,w=2,l=1,c=6) Returns a multi-line string format of the year's calendar, 3 months per row, with spacing distance c. The daily width spacing is w characters. Each line length is 21* W+18+2* C. l is the number of lines per week. |
| 2 | calendar.firstweekday( ) Returns the current setting for the starting day of the week. By default, when the calendar module is first loaded, it returns 0, i.e., Monday. |
| 3 | calendar.isleap(year) Returns True if it is a leap year, otherwise False. |
| 4 | calendar.leapdays(y1,y2) Returns the total number of leap years between y1 and y2. |
| 5 | calendar.month(year,month,w=2,l=1) Returns a multi-line string format of the year-month calendar, with two header lines and one line per week. The daily width spacing is w characters. The length of each line is 7* w+6. l is the number of lines per week. |
| 6 | calendar.monthcalendar(year,month) Returns a single-level nested list of integers. Each sublist contains integers representing a week. Dates outside the year-month are set to 0; days within the range are represented by the day of the month, starting from 1. |
| 7 | calendar.monthrange(year,month) Returns two integers. The first is the day of the week for the first day of the month, and the second is the number of days in the month. The day of the week ranges from 0 (Monday) to 6 (Sunday). (5, 30) explanation: 5 means the first day of November 2014 is Saturday, and 30 means November 2014 has a total of 30 days. |
| 8 | calendar.prcal(year, w=0, l=0, c=6, m=3) Equivalent to print (calendar.calendar(year, w=0, l=0, c=6, m=3)). |
| 9 | calendar.prmonth(theyear, themonth, w=0, l=0) Equivalent to print(calendar.month(theyear, themonth, w=0, l=0)). |
| 10 | calendar.setfirstweekday(weekday) Sets the starting day code for each week. 0 (Monday) to 6 (Sunday). |
| 11 | calendar.timegm(tupletime) The opposite of time.gmtime: accepts a time tuple format and returns the timestamp for that moment (floating-point seconds elapsed since the epoch 1970). |
| 12 | calendar.weekday(year,month,day) Returns the day code for the given date. 0 (Monday) to 6 (Sunday). Month is 1 (January) to 12 (December). |
Other Related Modules and Functions
Section titled “Other Related Modules and Functions”In Python, other modules for handling dates and times include: