Python3 Date and Time
Python programs can handle dates and times in many ways; converting date formats is a common task.
Python provides the time and calendar modules for formatting dates and times.
Time intervals are floating-point numbers in seconds.
Each timestamp is expressed as how much time has elapsed since midnight on January 1, 1970 (the epoch).
Python's time module has many functions for converting common date formats. For example, time.time() gets the current timestamp, as shown below:
Example
#!/usr/bin/python3
import
time
Import the time module
ticks
=
time
.
time
(
)
(
"The current timestamp is:"
,
ticks
)
The example above produces the following output:
当前时间戳为: 1459996086.7115328
Timestamp units are best suited for date arithmetic. However, dates before 1970 cannot be represented this way, nor can very distant dates; UNIX and Windows only support up to 2038.
What is a time tuple?
Many Python functions handle time using a tuple of 9 groups of numbers:
| No. | 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 Saving Time | -1, 0, 1; -1 is the flag determining whether daylight saving time is in effect |
The above is the struct_time tuple. This structure has the following attributes:
| No. | property | 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 daylight saving time is in effect: 1 (DST), 0 (not DST), -1 (unknown); defaults to -1 |
Get the current time
Converting from a floating-point timestamp to a time tuple is done by passing the float to a function such as localtime.
#!/usr/bin/python3
import time
localtime = time.localtime(time.time())
print ("本地时间为 :", localtime)
The example above produces the following output:
本地时间为 : 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 from various formats as needed, but the simplest function for a readable time pattern is asctime():
#!/usr/bin/python3
import time
localtime = time.asctime( time.localtime(time.time()) )
print ("本地时间为 :", localtime)
The example above produces the following output:
本地时间为 : Thu Apr 7 10:29:13 2016
Formatting dates
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
(
time
.
strftime
(
"%Y-%m-%d %H:%M:%S"
,
time
.
localtime
(
)
)
)
Format as Sat Mar 28 22:24:24 2016
(
time
.
strftime
(
"%a %b %d %H:%M:%S %Y"
,
time
.
localtime
(
)
)
)
Convert a format string to a timestamp
a
=
"Sat Mar 28 22:24:24 2016"
(
time
.
mktime
(
time
.
strptime
(
a
,
"%a %b %d %H:%M:%S %Y"
)
)
)
The example above produces the following output:
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 (00-99)
- %Y four-digit year (0000-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 abbreviated local weekday name
- %A full local weekday name
- %b abbreviated local month name
- %B full local month name
- %c local 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 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 name of the current time zone
- %% the % character itself
Get the 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:
Example
#!/usr/bin/python3
import
calendar
cal
=
calendar
.
month
(
2016
,
1
)
(
"The following outputs the calendar for January 2016:"
)
(
cal
)
The example above produces the following output:
The following outputs 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, both for handling time and for converting time formats:
| No. | Function and description | Example |
|---|---|---|
| 1 | time.altzone | |
| Returns the offset in seconds west of Greenwich for daylight saving time regions. If the region is east of Greenwich it returns a negative value (such as Western Europe, including the UK). Only applicable in regions where DST is enabled. |
The following example shows how to use 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" (Tuesday, December 11, 2008, 18:07:14). |
The following example shows 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 in seconds as a floating-point number. Used to measure the elapsed time of different programs; more useful than time.time(). |
Since this method depends on the operating system, it has been deprecated since Python 3.3 and removed in 3.8; use the following two functions instead.
time.perf_counter() # 返回系统运行时间 time.process_time() # 返回进程运行时间| | 4 | time.ctime([secs])
Equivalent to asctime(localtime(secs)); with no argument it is equivalent to asctime() |
The following example shows 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 (floating-point seconds since the 1970 epoch) and returns a time tuple t in Greenwich Mean Time. Note: t.tm_isdst is always 0 |
The following example shows 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]
Accepts a timestamp (floating-point seconds since the 1970 epoch) and returns a time tuple t in local time (t.tm_isdst can be 0 or 1 depending on whether DST is in effect locally at that 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 1970 epoch). | Example | | 8 | time.sleep(secs)
Suspends the calling thread for secs seconds. |
The following example shows how to use the sleep() function:
#!/usr/bin/python3 import time| | 9 | time.strftime(fmt[,tupletime])print ("Start : %s" % time.ctime()) time.sleep( 5 ) print ("End : %s" % time.ctime())
Accepts a time tuple and returns a readable string of local time whose format is determined by fmt. |
The following example shows 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 fmt. |
The following example shows how to use 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)
| | 11 | time.time( )
Returns the current time as a timestamp (floating-point seconds since the 1970 epoch). |
The following example shows how to use the time() function:
>>> import time >>> print(time.time()) 1459999336.1963577| | 12 | time.tzset()
Reinitializes time-related settings according to the environment variable TZ. | Example | | 13 | ** time.perf_counter()**
Returns the precise time of a timer (system uptime), including the 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 total CPU time executed by 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 2 very important attributes:
| No. | Attribute and description |
|---|---|
| 1 | time.timezone |
| The attribute time.timezone is the offset in seconds of the local time zone (without DST) from Greenwich (>0, Americas;<=0 most of Europe, Asia, Africa). | |
| 2 | time.tzname |
| The attribute time.tzname contains a pair of strings that vary by situation: the local time zone name with DST and the one without. |
The 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 the default last day. To change this, call calendar.setfirstweekday(). The module contains the following built-in functions:
| No. | Function and description |
|---|---|
| 1 | calendar.calendar(year,w=2,l=1,c=6) |
| Returns a multi-line string of the calendar for year year, with 3 months per row and a spacing of c. Each day is w characters wide. Each row is 21* W+18+2* C characters long.l is the number of rows per 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, i.e. Monday. | |
| 3 | calendar.isleap(year) |
是闰年返回 True,否则为 False。
>>> import calendar
>>> print(calendar.isleap(2000)) True >>> print(calendar.isleap(1900)) False | | 4 | calendar.leapdays(y1,y2)
Return the total number of leap years between the two years Y1 and Y2. | | 5 | calendar.month(year,month,w=2,l=1)
Return a calendar for the given year and month as a multi-line string, with two heading lines and one line per week. Each day is separated by w characters. Each line has length 7* w+6. l is the number of lines per week. | | 6 | calendar.monthcalendar(year,month)
Return a single-level nested list of integers. Each sublist holds the integers representing one week. Dates outside the given year and month are set to 0; dates within the range are represented by the day of the month, starting from 1. | | 7 | calendar.monthrange(year,month)
Returns two integers. The first is the weekday of the first day of the month, and the second is the number of days in the month. Weekdays range from 0 (Monday) to 6 (Sunday).
>>> import calendar >>> calendar.monthrange(2014, 11) (5, 30)
(5, 30) explained: 5 means the first day of November 2014 is a Saturday, and 30 means November 2014 has 30 days in total.
| | 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)
Set the starting weekday code for each week. 0 (Monday) to 6 (Sunday). | | 11 | calendar.timegm(tupletime)
The inverse of time.gmtime: accepts a time tuple and returns the timestamp for that moment (floating-point seconds elapsed since the 1970 epoch). | | 12 | calendar.weekday(year,month,day)
Return the weekday code for a given date. 0 (Monday) to 6 (Sunday). Months range from 1 (January) to 12 (December). |
Other related modules and functions
In Python, other modules for handling dates and times include: