Python 3 Date and Time

Python 3 Dates and Times

Python programs can manipulate dates and times in many ways, and converting date formats is a common function.

Python provides a time and calendar modules for formatting dates and times.

Time intervals are expressed as floating-point decimals expressed in seconds.

Each timestamp is expressed as the number of seconds since midnight, January 1, 1970 (the epoch).

Python’s time module provides many functions for converting between common date formats. For example, the function time.time() is used to obtain the current timestamp, as shown in the following example:

Example

#!/usr/bin/python3<br>
<br>
import time  # Import the time module<br>
<br>
ticks = time.time()<br>
print ("Current timestamp is:", ticks)<br>

The above example outputs:

Current timestamp is: 1459996086.7115328

Timestamp units are ideal for date calculations. However, dates before 1970 cannot be represented in this way. Dates that are too far in the future also cannot be represented in this way, as UNIX and Windows only support them until 2038.


What is a time tuple?

Many Python functions use a 9-digit array to process time:

Sequence Number 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 is a leap second)
6 Day of the week 0 to 6 (0 is Monday)
7 Day of the year 1 to 366 (Julian calendar)
8 Daylight Saving Time -1, 0, 1, -1 are flags that determine whether daylight saving time is in effect

This is the struct_time tuple. This structure has the following attributes:

Order Number 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 is a leap second)
6 tm_wday 0 to 6 (0 is Monday)
7 tm_yday Day of the year, 1 to 366
8 tm_isdst Whether daylight saving time is in effect. Values are: 1 (daylight saving time), 0 (not daylight saving time), -1 (unknown). Default is -1.

Getting the Current Time

To convert a floating-point timestamp to a time tuple, pass the floating-point value to a function like localtime.

#!/usr/bin/python3

import time

localtime = time.localtime(time.time())
print ("Local time is:", localtime)

The above example outputs:

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 a formatted time

You can choose a variety of formats depending on your needs, but the simplest function for getting a readable time format is asctime():

#!/usr/bin/python3

import time

localtime = time.asctime( time.localtime(time.time()) )
print ("Local time is:", localtime)

The above example outputs:

Local time is: Thu Apr 7 10:29:13 2016

Formatting a date

We can use the strftime method of the time module to format a date:

time.strftime(format[, t])
#!/usr/bin/python3

import time

# Format to 2016-03-20 11:45:39
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# Format to Sat Mar 28 22:24:24 2016
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))

# Convert the format 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")))

The above example outputs:

2016-04-07 10:29:46
Thu Apr 07 10:29:46 2016
1459175064.0

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 hour (0-23)
  • %I Hour in 12-hour format (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 corresponding date and time representation
  • %j Day of the year (001-366)
  • %p Locale’s equivalent of A.M. or P.M.
  • %U Week of the year (00-53), starting on Sunday
  • %w Day of the week (0-6), starting on Sunday
  • %W Week number of the year (00-53), Monday as the first day of the week.
  • %x Locale-specific date representation.
  • %X Locale-specific time representation.
  • %Z Current time zone name.
  • %% The % sign itself.

Getting a Month’s Calendar.

The Calendar module has extensive methods for manipulating yearly and monthly calendars. For example, to print a calendar for a specific month:

#!/usr/bin/python3

import calendar

cal = calendar.month(2016, 1)
print ("The following prints the calendar for January 2016:")
print (cal)

The above example outputs:

The following prints 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 contains the following built-in functions, both for time processing and for converting time formats:

Serial Number Example
1 time.altzone
Returns the time zone’s daylight saving time offset in seconds west of Greenwich. Returns a negative value if the zone is east of Greenwich (e.g., Western Europe, including the United Kingdom). This function is only available for regions with daylight saving time enabled.
The following example demonstrates the use of the altzone() function:

>>> import time
>>> print ("time.altzone %d " % time.altzone)
time.altzone -28800
2 time.asctime([tupletime])
Accepts a time tuple and returns a readable 24-character string of the form “Tue Dec 11 18:07:14 2008”.
The following example demonstrates how to use the asctime() function:

>>> import time
>>> t = time.localtime()
>>> print ("time.asctime(t): %s " % time.asctime(t))
time.asctime(t): Thu Apr 7 10:36:20 2016
3 time.clock()
Returns the current CPU time as a floating-point number in seconds. This is more useful than time.time() for measuring the time taken by different programs.
Example
Because this method depends on the operating system, it is deprecated in Python 3.3 and later, and was removed in version 3.8. Use the following two functions instead.

time.perf_counter() # Returns system uptime
time.process_time() # Returns process uptime
4 time.ctime([secs])
Equivalent to asctime(localtime(secs)) . If no argument is given, it is equivalent to asctime()
The following example demonstrates how to use the ctime() function:

>>> import time
>>> print ("time.ctime() : %s" % time.ctime())
time.ctime() : Thu Apr 7 10:51:58 2016
5 time.gmtime([secs])
Accepts a timestamp (a floating-point number of seconds since the epoch) and returns a time-tuple t in Greenwich Mean Time. Note: t.tm_isdst is always 0.

The following example demonstrates how to use the gmtime() function:

>>> import time
>>> print (“gmtime :”, time.gmtime(1455508609.34375))
gmtime : time.struct_time(tm_year=2016, 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 (a floating-point number of seconds since the epoch) and returns a time-tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether the local time is daylight saving time).
The following example shows how to use the localtime() function:

>>> import time
>>> print ("localtime(): ", time.localtime(1455508609.34375))
localtime(): time.struct_time(tm_year=2016, 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 (floating point seconds since the epoch).
Example
8 time.sleep(secs)
Delays the execution of the calling thread, where secs refers to the number of seconds.
The following example shows how to use the sleep() function:

#!/usr/bin/python3
import time

print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())
9 time.strftime(fmt[,tupletime])
Accepts a time tuple and returns the local time as a readable string in the format determined by fmt.
The following example demonstrates how to use the strftime() function:

>>> import time
>>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
2016-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 specified by fmt.
The following example demonstrates how to use the strptime() function:

>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print ("Return tuple: ", struct_time)
Return 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 (a floating-point number of seconds since the epoch).
The following example demonstrates how to use the time() function:

>>> import time
>>> print(time.time())
1459999336.1963577
12 time.tzset()
Reinitializes time-related settings based on the environment variable TZ.
Example
13
time.perf_counter()

Returns the precise time of the counter (the system’s running time), including all system sleep times. Since the return value is based on an undefined basis, only the difference between successive calls is valid.

Example
14
time.process_time()

Returns the CPU time of the current process. The sum of the times, excluding sleep time. Since the return value’s reference point is undefined, only the difference between successive calls is valid.

 

The Time module contains the following two important properties:

Sequence Number
1 time.timezone
The time.timezone attribute is the offset in seconds from Greenwich Mean Time (>0 for the Americas; <=0 for most of Europe, Asia, and Africa) for the local time zone (when daylight saving time is not in effect).
2 time.tzname
The time.tzname attribute contains a pair of strings that vary depending on the context. , respectively, the local time zone name with and without daylight saving time.

Calendar Module

This module contains functions related to the calendar, such as printing a text calendar for a particular month.

Monday is the default first day of the week, and Sunday is the default last day. To change this setting, call calendar.setfirstweekday(). The module includes the following built-in functions:

1 calendar.calendar(year,w=2,l=1,c=6)
Returns a multi-line calendar for year, with three months per line, spaced c apart. Daily widths are spaced w characters apart. Each line is 21*W+18+2*C. l is the number of lines per week.
2 calendar.firstweekday()
Returns the current setting for the start of the week. By default, this returns 0 (Monday) when the caendar module is first loaded.
3 calendar.isleap(year)
Returns True if the year is a leap year, false otherwise.

>>> import calendar
>>> print(calendar.isleap(2000))
True
>>> print(calendar.isleap(1900))
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 calendar for year and month, with two header lines and one line for each week. The daily interval is w characters. Each line is 7* w+6. l is the number of rows per week.
6 calendar.monthcalendar(year,month)
Returns a single nested list of integers. Each sublist contains an integer representing a week. Days outside the year and month ranges are set to 0; days within the range are represented by the day of the month, starting at 1.
7 calendar.monthrange(year,month)
Returns two integers. The first is the day of the week, and the second is the number of days in the month. Days of the week range from 0 (Monday) to 6 (Sunday).

>>> import calendar
>>> calendar.monthrange(2014, 11)
(5, 30)

(5, 30) Explanation: 5 represents November 2014. The first day of the month is Saturday, so 30 means there are 30 days in November 2014.

8 calendar.prcal(year,w=2,l=1,c=6)
is equivalent to print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
is equivalent to print calendar.calendar(year, w, l, c).
10 calendar.setfirstweekday(weekday)
Sets the first day of the week. 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
The opposite of time.gmtime: accepts a time tuple and returns the timestamp of that moment (floating point seconds since the epoch).
12 calendar.weekday(year,month,day)
Returns the day code for the given date. 0 (Monday) to 6 (Sunday). Months are 1 (January) to 12 (December).

Other related modules and functions

Other modules for handling dates and times in Python include:

  • time module
  • datetime module

Leave a Reply

Your email address will not be published. Required fields are marked *