YouTip LogoYouTip

Python3 Date Time

Python3 Date and Time

Python3 Date and Time

Python programs can handle date and time in many ways. Converting date formats is a common functionality.

Python provides the time and calendar modules to help format dates and times.

Time intervals are floating-point numbers in units of seconds.

Each timestamp represents the time elapsed since midnight (the epoch) of January 1, 1970.

The Python time module provides many functions to convert common date formats. For example, the function time.time() 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:", ticks)

The output of the above example is:

Current timestamp: 1459996086.7115328

Timestamps are best suited for date arithmetic. However, dates before 1970 cannot be represented this way. Very distant dates are also not supported; UNIX and Windows only support up to the year 2038.


What is a Time Tuple?

Many Python functions use a time tuple, which is a tuple of 9 numbers, to handle time:

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 calendar)
8 Daylight savings -1, 0, 1, where -1 indicates the decision for daylight savings

The above is also known as a 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 it is daylight savings time. Values: 1 (yes), 0 (no), -1 (unknown). Default is -1.

Getting the Current Time

To convert a timestamp (a floating-point number) to a time tuple, simply pass the floating-point number to a function like localtime.

#!/usr/bin/python3
import time

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

The output of the above example is:

Local time: 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 choose from various formats according to your needs, but the simplest function to get a readable time string is asctime():

#!/usr/bin/python3
import time

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

The output of the above example is:

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


Formatting Dates

We can use the strftime method of the time module 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 format string to timestamp
a = "Sat Mar 28 22:24:24 2016"
print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))

The output of the above example is:

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

Python date and time formatting symbols:

  • %y Two-digit year representation (00-99)
  • %Y Four-digit year representation (0000-9999)
  • %m Month (01-12)
  • %d Day of the month (0-31)
  • %H Hour (24-hour clock) (0-23)
  • %I Hour (12-hour clock) (01-12)
  • %M Minute (00-59)
  • %S Second (00-59)
  • %a Local abbreviated weekday name
  • %A Local full weekday name
  • %b Local abbreviated month name
  • %B Local full month name
  • %c Local appropriate date and time representation
  • %j Day of the year (001-366)
  • %p Local equivalent of A.M. or P.M.
  • %U Week number of the year (00-53), where Sunday is the first day of the week
  • %w Weekday (0-6), where Sunday is the first day of the week
  • %W Week number of the year (00-53), where Monday is the first day of the week
  • %x Local appropriate date representation
  • %X Local appropriate time representation
  • %Z Current time zone name
  • %% Literal '%' character

Getting a Month's Calendar

The calendar module has extensive methods for handling year and month calendars, such as printing the calendar for a specific month:

Example

#!/usr/bin/python3

import calendar

cal = calendar.month(2016, 1)
print("Here is the calendar for January 2016:")
print(cal)

The output of the above example is:

Here is 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


The Time Module

The time module contains the following built-in functions, including those for time processing and time format conversion:

Index Function and Description Example
1 time.altzone
Returns the offset of the local (non-Daylight Saving) timezone in seconds west of UTC (positive in the Americas, negative in most of Europe, Asia, Africa). Only available if daylight saving time is 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()
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 the use of 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. Useful for measuring the elapsed time of different programs, more so than time.time().

Note: This method is deprecated since Python 3.3 and removed in 3.8. Use the following two functions instead:
time.perf_counter() # Returns system running time
time.process_time() # Returns process running time
Example
4 time.ctime()
Equivalent to asctime(localtime(secs)). Without arguments, it is equivalent to asctime().
The following example demonstrates the use of the ctime() function:
>>> import time
>>> print("time.ctime() : %s" % time.ctime())
time.ctime() : Thu Apr 7 10:51:58 2016
5 time.gmtime()
Accepts a timestamp (floating-point seconds elapsed since the epoch) and returns a time tuple t in UTC. Note: t.tm_isdst is always 0.
The following example demonstrates the use of 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()
Accepts a timestamp (floating-point seconds elapsed since the epoch) and returns a time tuple t in local time. t.tm_isdst can be 0 or 1, depending on whether daylight saving time is in effect locally.
The following example demonstrates the use of 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 elapsed since the epoch).
Example
8 time.sleep(secs)
Delays the execution of the calling thread for the given number of seconds.
The following example demonstrates the use of 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 a readable string representing the local time, formatted according to fmt.
The following example demonstrates the use of 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 according to the format fmt and returns a time tuple.
The following example demonstrates the use of the strptime() function:
>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print("Returned tuple: ", struct_time)
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 timestamp as a floating-point number (seconds elapsed since the epoch).
The following example demonstrates the use of the time() function:
>>> import time
>>> print(time.time())
1459999336.1963577
12 time.tzset()
Reinitializes the time-related settings based on the environment variable TZ.
Example
13 time.perf_counter()
Returns the precise time of the timer (system running time), including the entire system's sleep time. Since the reference point of the return value is undefined, only the difference between consecutive calls is meaningful.
Example
14 time.process_time()
Returns the sum of CPU time for the current process, excluding sleep time. Since the reference point of the return value is undefined, only the difference between consecutive calls is meaningful.

The time module contains the following two very important attributes:

Index Attribute and Description
1 time.timezone
The attribute time.timezone is the offset of the local (non-Daylight Saving) timezone in seconds west of UTC (>0 in the Americas; <=0 in most of Europe, Asia, Africa).
2 time.tzname
The attribute time.tzname is a tuple of two strings: the local timezone name with daylight saving, and without.

The Calendar Module

The functions in this module are related to calendars, such as printing the character calendar for a specific month.

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

Index Function and Description
1 calendar.calendar(year, w=2, l=1, c=6)
Returns a multi-line string format calendar for the given year, with 3 months per line and a spacing of c. The width of each day is w characters. The length of each line is 21*w + 18 + 2*c. l is the number of lines for each week.
2 calendar.firstweekday()
Returns the current setting for the first day of the week. By default, when the calendar module is first loaded, it returns 0, which is Monday.
3 calendar.isleap(year)
Returns True if the year is a leap year, otherwise False.
>>> 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 the years Y1 and Y2.
5 calendar.month(year, month, w=2, l=1)
Returns a multi-line string format calendar for the given month of the given year, with a two-line header and one week per line. The width of each day is w characters. The length of each line is 7*w + 6. l is the number of lines for each week.
6 calendar.monthcalendar(year, month)
Returns a single-layer nested list of integers. Each sublist contains integers representing a week. Days outside the month are set to 0; days within the month 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 is from 0 (Monday) to 6 (Sunday).
>>> import calendar
>>> calendar.monthrange(2014, 11)
(5, 30)

Explanation: 5 indicates that the first day of November 2014 is a Saturday, and 30 indicates that 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 first day of the week code. 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
The inverse of time.gmtime(): accepts a time tuple and returns the corresponding timestamp (floating-point seconds elapsed 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

In Python, other modules for handling date and time include:

← Linux Comm LetPython3 Date Time β†’