Python Tutorial (39) - Date and Time

Time: Column:Python views:269

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:

IndexFieldValue
04-digit year2008
1Month1 to 12
2Day1 to 31
3Hour0 to 23
4Minute0 to 59
5Second0 to 61 (60 or 61 are leap seconds)
6Day of the week0 to 6 (0 is Monday)
7Day of the year1 to 366 (Julian day)
8Daylight saving flag-1, 0, 1 (-1 means unspecified)

This structure is referred to as the struct_time tuple. It has the following attributes:

IndexAttributeValue
0tm_year2008
1tm_mon1 to 12
2tm_mday1 to 31
3tm_hour0 to 23
4tm_min0 to 59
5tm_sec0 to 61 (leap seconds)
6tm_wday0 to 6 (0 is Monday)
7tm_ydayDay of the year, 1 to 366
8tm_isdst1 (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 DescriptionExample
1time.altzoneReturns 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
2time.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
3time.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
4time.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
5time.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)
6time.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)
7time.mktime(tupletime)Accepts a time tuple and returns a timestamp (the number of floating-point seconds since the epoch).
8time.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>
9time.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
10time.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)
11time.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>
12time.tzset()Reinitializes time-related settings according to the environment variable TZ.
13time.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.
14time.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
1time.timezone
2time.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
1calendar.calendar(year,w=2,l=1,c=6)
2calendar.firstweekday()
3calendar.isleap(year)
4calendar.leapdays(y1,y2)
5calendar.month(year,month,w=2,l=1)
6calendar.monthcalendar(year,month)
7calendar.monthrange(year,month)
8calendar.prcal(year, w=0, l=0, c=6, m=3)
9calendar.prmonth(theyear, themonth, w=0, l=0)
10calendar.setfirstweekday(weekday)
11calendar.timegm(tupletime)
12calendar.weekday(year,month,day)

Other Related Modules and Functions

In Python, other modules for handling dates and times include:

  • Time module

  • Datetime module