Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Dates and Times

Python Dates and Times

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 represented by how much time has elapsed since midnight on January 1, 1970 (the epoch).

The time module in Python has many functions that can convert common date formats. For example, the function time.time() is used to get the current timestamp, as in the following example:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

time

Import the time module

ticks

=

time

.

time

(

)

print

"

The current timestamp is:

"

,

ticks

The example above produces the following output:


当前时间戳为: 1459994552.51

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 are flags determining whether it is daylight saving time

The above is also 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 1 to 366 (Julian calendar)
8 tm_isdst -1, 0, 1, -1 are flags determining whether it is daylight saving time

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.

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

time

localtime

=

time

.

localtime

(

time

.

time

(

)

)

print

"

Local time is:

"

,

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=3, tm_sec=27, 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():

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

time

localtime

=

time

.

asctime

(

time

.

localtime

(

time

.

time

(

)

)

)

print

"

Local time is:

"

,

localtime

The example above produces the following output:


本地时间为 : Thu Apr  7 10:05:21 2016

Formatting dates

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


time.strftime(format[, t])

Example demonstration:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

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 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 example above produces the following output:


2016-04-07 10:25:09
Thu Apr 07 10:25:09 2016
1459175064.0

Date and time formatting symbols in Python:


Get the calendar for a month

The Calendar module has a wide range of methods for handling annual and monthly calendars, such as printing the calendar for a given month:

Example (Python 2.0+)

#!/usr/bin/python

-- coding: UTF-8 --

import

calendar

cal

=

calendar

.

month

(

2016

,

1

)

print

"

The following outputs the calendar for January 2016:

"

print

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
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.
2 time.asctime([tupletime])
Accepts a time tuple and returns a readable 24-character string in the form "Tue Dec 11 18:07:14 2008" (18:07:14, Tuesday, December 11, 2008).
3 time.clock( )
Returns the current CPU time in seconds as a floating-point number. Used to measure the time consumed by different programs, it is more useful than time.time().
4 time.ctime([secs])
Equivalent to asctime(localtime(secs)); with no argument, it is equivalent to asctime()
5 time.gmtime([secs])
Accepts a timestamp (floating-point seconds elapsed since the 1970 epoch) and returns the time tuple t in Greenwich Mean Time. Note: t.tm_isdst is always 0
6 time.localtime([secs])
Accepts a timestamp (floating-point seconds elapsed since the 1970 epoch) and returns the time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether it is daylight saving time locally at that time).
7 time.mktime(tupletime)
Accepts a time tuple and returns a timestamp (floating-point seconds elapsed since the 1970 epoch).
8 time.sleep(secs)
Delays the execution of the calling thread; secs refers to the number of seconds.
9 time.strftime(fmt[,tupletime])
Accepts a time tuple and returns the local time as a readable string, with the format determined by fmt.
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
Parses a time string into a time tuple according to the format of fmt.
11 time.time( )
Returns the timestamp of the current time (the floating-point number of seconds elapsed since the 1970 epoch).
12 time.tzset()
Reinitializes time-related settings according to the environment variable TZ.

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 daylight saving time) from Greenwich (>0 for the 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 containing the calendar for the year, with 3 months per line and a spacing of c. The daily width interval is w characters. Each line has a length of 21* W+18+2* C. l is the number of lines 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)
Returns the total number of leap years between the two years Y1 and Y2. | | 5 calendar.month(year,month,w=2,l=1)
Returns a calendar in a multi-line string format for year and month, with two header lines and one line per week. The width interval for each day is w characters. The length of each line is 7* w+6. l is the number of lines per week. | | 6 | calendar.monthcalendar(year,month)
Returns a single-level nested list of integers. Each sublist holds integers representing a week. Dates outside of Year and month are all set to 0; days within the range are represented by the day number of the month, starting from 1. | | 7 calendar.monthrange(year,month)
Returns two integers. The first is the day code of the weekday of that month, the second is the date code of that month. Days from 0 (Monday) to 6 (Sunday); months from 1 to 12. | | 8 calendar.prcal(year,w=2,l=1,c=6)
is equivalent to print calendar.calendar(year,w=2,l=1,c=6). | | 9 | calendar.prmonth(year,month,w=2,l=1)
is equivalent to print calendar.month(year,month,w=2,l=1) . | | 10 | calendar.setfirstweekday(weekday)
Sets the starting day code of each week. 0 (Monday) to 6 (Sunday). | | 11 calendar.timegm(tupletime)
Opposite to time.gmtime: accepts a time tuple form, returns the timestamp of that moment (floating-point seconds elapsed since the 1970 epoch). | | 12 | calendar.weekday(year,month,day)
Returns the day code of a given date. 0 (Monday) to 6 (Sunday). Month is from 1 (January) to 12 (December). |


Other Related Modules and Functions

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