Python3 Date and Time

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

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 expressed as how long it has been since midnight (epoch) on January 1, 1970.

There are many functions in Python's time module that can convert common date formats. For example, the function time.time() is used to get the current timestamp, as in the example below:

Examples

#!/usr/bin/python3

import time  # import time module

ticks = time.time()
print ("Current timestamp:", ticks)

The output of the above example is:

当前时间戳为: 1459996086.7115328

Timestamp units are most suitable for date arithmetic. However, dates before 1970 cannot be represented this way. Dates too far in the future are also not possible, as UNIX and Windows only support up to 2038.



What is a time tuple?

Many Python functions process time using a tuple of 9 groups of numbers:

No.FieldValue
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 calendar)
8Daylight saving time-1, 0, 1, -1 is a flag determining whether it is daylight saving time

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

No.AttributeValue
0tm_year2008
1tm_mon1 to 12
2tm_mday1 to 31
3tm_hour0 to 23
4tm_min0 to 59
5tm_sec0 to 61 (60 or 61 are leap seconds)
6tm_wday0 to 6 (0 is Monday)
7tm_ydayDay of the year, 1 to 366
8tm_isdstWhether it is daylight saving time, values: 1 (daylight saving time), 0 (not daylight saving time), -1 (unknown), default -1


Get current time

To convert from a timestamp returning a floating-point number to a time tuple, just pass the floating-point number to functions like localtime.

#!/usr/bin/python3

import time

localtime = time.localtime(time.time())
print ("本地时间为 :", localtime)

The output of the above example 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)


Get formatted time

You can choose various formats according to your needs, but the simplest function for obtaining a readable time pattern is asctime():

#!/usr/bin/python3

import time

localtime = time.asctime( time.localtime(time.time()) )
print ("本地时间为 :", localtime)

The output of the above example is:

本地时间为 : Thu Apr  7 10:29:13 2016

Format dates

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

time.strftime(format[, t])

Examples

#!/usr/bin/python3

import time

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

# Format into Sat Mar 28 22:24:24 2016 form
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

Time and date 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 Hour in 24-hour format (0-23)
  • %I Hour in 12-hour format (01-12)
  • %M Minutes (00-59)
  • %S Seconds (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), Sunday is the start of the week
  • %w Weekday (0-6), Sunday is the start of the week
  • %W Week number of the year (00-53), Monday is the start of the week
  • %x Local appropriate date representation
  • %X Local appropriate time representation
  • %Z Name of the current time zone
  • %% The percent sign itself

Get calendar for a month

The Calendar module has a wide range of methods for handling yearly and monthly calendars, for example printing a month's calendar:

Examples

#!/usr/bin/python3

import calendar

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

The output of the above example is:

以下输出2016年1月份的日历:
    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:

No.Function and descriptionExamples
1time.altzone
Returns the offset in seconds for daylight saving time zones west of Greenwich. If the region is east of Greenwich, a negative value is returned (e.g., Western Europe, including the UK). It is only available in regions where daylight saving time is enabled.

The following example demonstrates the usage of the altzone() function:

>>> import time
>>> print ("time.altzone %d " % time.altzone)
time.altzone -28800 
2time.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 demonstrates the usage 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 
3time.clock()
Returns the current CPU time in floating-point seconds. It is used to measure the time consumption of different programs, and is more useful than time.time().

Examples

Because this method depends on the operating system, it is not recommended after Python 3.3, and was removed in version 3.8; the following two functions should be used instead.

time.perf_counter()  # 返回系统运行时间
time.process_time()  # 返回进程运行时间
4time.ctime([secs])
Its effect is equivalent to asctime(localtime(secs)); if no argument is given, it is equivalent to asctime().

The following example demonstrates the usage of the ctime() function:

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

The following example demonstrates the usage 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)
6time.localtime([secs]
Receives a timestamp (floating-point seconds elapsed since the 1970 epoch) and returns the time tuple t under local time (t.tm_isdst can be 0 or 1, depending on whether it is daylight saving time at that time in the local area).

The following example demonstrates the usage 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)
7time.mktime(tupletime)
Accepts a time tuple and returns a timestamp (floating-point seconds elapsed since the 1970 epoch).
Examples
8time.sleep(secs)
Delays the execution of the calling thread, where secs refers to seconds.

The following example demonstrates the usage of the sleep() function:

#!/usr/bin/python3
import time

print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())
9time.strftime(fmt[,tupletime])
Receives a time tuple and returns the local time represented as a readable string, with the format determined by fmt.

The following example demonstrates the usage of the strftime() function:

>>> import time
>>> print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
2016-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 of fmt.

The following example demonstrates the usage of the strptime() function:

>>> import time
>>> struct_time = time.strptime("30 Nov 00", "%d %b %y")
>>> print ("返回元组: ", struct_time)
返回元组:  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 timestamp of the current time (floating-point seconds elapsed since the 1970 epoch).

The following example demonstrates the usage of the time() function:

>>> import time
>>> print(time.time())
1459999336.1963577
12time.tzset()
Reinitializes time-related settings according to the environment variable TZ.
Examples
13 time.perf_counter()
Returns the precise time of the timer (system uptime), including sleep time of the entire system. Since the reference point of the return value is undefined, only the difference between results of consecutive calls is valid.
Examples
14 time.process_time()
Returns the total CPU time executed by the current process, not including sleep time. Since the reference point of the return value is undefined, only the difference between results of consecutive calls is valid.
 

The Time module contains the following 2 very important attributes:

No.Attribute and description
1time.timezone
The attribute time.timezone is the offset in seconds of the local time zone (when daylight saving time is not in effect) from Greenwich (>0, Americas; <=0 most of Europe, Asia, Africa).
2time.tzname
The attribute time.tzname contains a pair of strings that vary depending on the situation: the local timezone name with daylight saving time, and the one without.


Calendar Module

The functions in this module are all calendar-related, such as printing a character calendar for a month.

Monday is the default first day of the week, and Sunday is the default last day. To change the 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)
Return a multi-line string format calendar for year, with 3 months per line and interval distance c. The daily width interval is w characters. Each line length is21* W+18+2* C。lIt is the number of lines per week.
2calendar.firstweekday( )
Return 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.
3calendar.isleap(year)

Return True if it is a leap year, otherwise False.

>>> import calendar
>>> print(calendar.isleap(2000))
True
>>> print(calendar.isleap(1900))
False
4calendar.leapdays(y1,y2)
Return the total number of leap years between the two years Y1 and Y2.
5calendar.month(year,month,w=2,l=1)
Return a multi-line string format calendar for month month of year year, with two header lines, one week per line. The daily width interval is w characters. The length of each line is 7*w+6. l is the number of lines per week.
6calendar.monthcalendar(year,month)
Return a single-level nested list of integers. Each sublist contains integers representing one week. Dates outside the month month of year year are set to 0; dates within the range are represented by the day of the month, starting from 1.
7calendar.monthrange(year,month)

Return two integers. The first is the weekday of the month, and the second is the number of days in the month. Weekdays are from 0 (Monday) to 6 (Sunday).

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

(5, 30) Explanation: 5 means the first day of November 2014 is Saturday, and 30 means November 2014 has a total of 30 days.

8calendar.prcal(year, w=0, l=0, c=6, m=3)
Equivalent to print (calendar.calendar(year, w=0, l=0, c=6, m=3)).
9calendar.prmonth(theyear, themonth, w=0, l=0)
Equivalent toprint(calendar.month(theyear, themonth, w=0, l=0))。
10calendar.setfirstweekday(weekday)
Set the starting day code of each week. From 0 (Monday) to 6 (Sunday).
11calendar.timegm(tupletime)
The opposite of time.gmtime: accepts a time tuple and returns the timestamp of that moment (floating-point seconds since the 1970 epoch).
12calendar.weekday(year,month,day)
Return the weekday code for the given date. 0 (Monday) to 6 (Sunday). The month is from 1 (January) to 12 (December).


Other related modules and functions

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

Other extensions