Python Date and Time Handling
Date and time manipulation is a common functionality in Python programs. Python provides time
and calendar
modules for formatting and working with dates and times.
Time intervals are represented as floating-point numbers in seconds.
Every timestamp represents the time elapsed since midnight on January 1, 1970 (the epoch).
The time
module in Python includes several functions to convert commonly used date formats. For example, the time.time()
function is used to get the current timestamp, as shown in the following example:
Example:
#!/usr/bin/python3 import time # Import the time module ticks = time.time() print("Current timestamp is:", ticks)
Output:
Current timestamp is: 1459996086.7115328
Timestamps are ideal for date calculations, but dates before 1970 cannot be represented using them. Additionally, very distant dates are not supported, as UNIX and Windows systems only support dates up until 2038.
What is a Time Tuple?
Many Python functions process time as a tuple containing 9 elements:
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 the week | 0 to 6 (0 is Monday) |
7 | Day of the year | 1 to 366 (Julian day) |
8 | Daylight saving flag | -1, 0, 1 (-1 means unspecified) |
This structure is referred to as the struct_time
tuple. It 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 (leap seconds) |
6 | tm_wday | 0 to 6 (0 is Monday) |
7 | tm_yday | Day of the year, 1 to 366 |
8 | tm_isdst | 1 (daylight saving), 0 (no daylight saving), or -1 (unknown) |
Getting the Current Time
To convert a floating-point timestamp to a time tuple, pass the floating-point number to functions like localtime
.
Example:
#!/usr/bin/python3 import time localtime = time.localtime(time.time()) print("Local time is:", localtime)
Output:
Local time is: time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=28, tm_sec=49, tm_wday=3, tm_yday=98, tm_isdst=0)
Getting Formatted Time
You can format the date and time in various ways. The simplest function to get a readable time format is asctime()
:
Example:
#!/usr/bin/python3 import time localtime = time.asctime(time.localtime(time.time())) print("Local time is:", localtime)
Output:
Local time is: Thu Apr 7 10:29:13 2016
This basic approach helps format and work with date and time effectively in Python, allowing for flexible and readable output.
Formatting Dates in Python
In Python, we can use the time
module's strftime
method to format dates:
time.strftime(format[, t])
Example
#!/usr/bin/python3 import time # Format as '2016-03-20 11:45:39' print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # Format as 'Sat Mar 28 22:24:24 2016' print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # Convert a formatted string to a timestamp a = "Sat Mar 28 22:24:24 2016" print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
Output:
2016-04-07 10:29:46 Thu Apr 07 10:29:46 2016 1459175064.0
Python Time and Date Formatting Symbols:
%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
: Hour (00-23, 24-hour format)%I
: Hour (01-12, 12-hour format)%M
: Minute (00-59)%S
: Seconds (00-59)%a
: Shortened weekday name%A
: Full weekday name%b
: Shortened month name%B
: Full month name%c
: Local date and time representation%j
: Day of the year (001-366)%p
: Local AM/PM equivalent%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
: Local date representation%X
: Local time representation%Z
: Current time zone name%%
: Literal percent sign
Getting a Month's Calendar
The calendar
module provides methods for working with yearly and monthly calendars, such as printing a month's calendar:
Example
#!/usr/bin/python3 import calendar cal = calendar.month(2016, 1) print("The calendar for January 2016:") print(cal)
Output:
The calendar for January 2016: January 2016 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Time Module
The Time module includes the following built-in functions for both time processing and converting time formats:
No. | Function and Description | Example |
---|---|---|
1 | time.altzone | Returns the offset in seconds for daylight saving time in regions west of Greenwich. If the area is east of Greenwich (like Western Europe, including the UK), it returns a negative value. This is applicable only for areas that observe daylight saving time. Example: python<br>import time<br>print ("time.altzone %d " % time.altzone)<br> Output: time.altzone -28800 |
2 | time.asctime([tupletime]) | Accepts a time tuple and returns a readable string in the format "Tue Dec 11 18:07:14 2008" (December 11, 2008, Tuesday, 18:07:14). Example: python<br>import time<br>t = time.localtime()<br>print ("time.asctime(t): %s " % time.asctime(t))<br> Output: time.asctime(t): Thu Apr 7 10:36:20 2024 |
3 | time.clock() | Returns the current CPU time in seconds as a floating-point number. This is used to measure the time taken by different programs, more useful than time.time() . Note: This method is deprecated after Python 3.3 and removed in version 3.8; use the following two functions instead: - time.perf_counter() # Returns the system running time - time.process_time() # Returns the process running time |
4 | time.ctime([secs]) | Equivalent to asctime(localtime(secs)) ; if no parameter is given, it is equivalent to asctime() . Example: python<br>import time<br>print ("time.ctime() : %s" % time.ctime())<br> Output: time.ctime() : Thu Apr 7 10:51:58 2024 |
5 | time.gmtime([secs]) | Receives a timestamp (the number of floating-point seconds since the epoch, January 1, 1970) and returns a time tuple t in Greenwich Mean Time. Note: t.tm_isdst is always 0. Example: python<br>import time<br>print ("gmtime :", time.gmtime(1455508609.34375))<br> Output: gmtime : time.struct_time(tm_year=2024, tm_mon=2, tm_mday=15, tm_hour=3, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0) |
6 | time.localtime([secs]) | Receives a timestamp (the number of floating-point seconds since the epoch) and returns a local time tuple t (where t.tm_isdst can be 0 or 1, depending on whether it is currently daylight saving time). Example: python<br>import time<br>print ("localtime(): ", time.localtime(1455508609.34375))<br> Output: localtime(): time.struct_time(tm_year=2024, tm_mon=2, tm_mday=15, tm_hour=11, tm_min=56, tm_sec=49, tm_wday=0, tm_yday=46, tm_isdst=0) |
7 | time.mktime(tupletime) | Accepts a time tuple and returns a timestamp (the number of floating-point seconds since the epoch). |
8 | time.sleep(secs) | Delays the execution of the calling thread for secs seconds. Example: python<br>#!/usr/bin/python3<br>import time<br>print ("Start : %s" % time.ctime())<br>time.sleep( 5 )<br>print ("End : %s" % time.ctime())<br> |
9 | time.strftime(fmt[,tupletime]) | Accepts a time tuple and returns a readable string representing the local time, formatted according to fmt . Example: python<br>import time<br>print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))<br> Output: 2024-04-07 11:18:05 |
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 . Example: python<br>import time<br>struct_time = time.strptime("30 Nov 00", "%d %b %y")<br>print ("Returned tuple: ", struct_time)<br> Output: Returned tuple: time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1) |
11 | time.time() | Returns the current time as a timestamp (the number of floating-point seconds since the epoch). Example: python<br>import time<br>print(time.time())<br> |
12 | time.tzset() | Reinitializes time-related settings according to the environment variable TZ . |
13 | time.perf_counter() | Returns the precise time of the timer (system running time), including the sleep time of the whole system. Since the baseline for the return value is undefined, only the difference between consecutive calls is valid. |
14 | time.process_time() | Returns the total CPU time for the current process, excluding sleep time. Similarly, only the difference between consecutive calls is valid. |
The Time module includes the following two very important attributes:
No. | Attribute and Description |
---|---|
1 | time.timezone |
2 | time.tzname |
Calendar Module
This module contains functions related to calendars, such as printing a character calendar for a given month.
By default, Monday is the first day of the week, and Sunday is the last day. To change this setting, call the calendar.setfirstweekday()
function. The module includes the following built-in functions:
No. | Function and Description |
---|---|
1 | calendar.calendar(year,w=2,l=1,c=6) |
2 | calendar.firstweekday() |
3 | calendar.isleap(year) |
4 | calendar.leapdays(y1,y2) |
5 | calendar.month(year,month,w=2,l=1) |
6 | calendar.monthcalendar(year,month) |
7 | calendar.monthrange(year,month) |
8 | calendar.prcal(year, w=0, l=0, c=6, m=3) |
9 | calendar.prmonth(theyear, themonth, w=0, l=0) |
10 | calendar.setfirstweekday(weekday) |
11 | calendar.timegm(tupletime) |
12 | calendar.weekday(year,month,day) |
Other Related Modules and Functions
In Python, other modules for handling dates and times include:
Time module
Datetime module