Python Date and Time
Python programs can handle dates and times in many ways, and converting date formats is a common feature.
Python provides time and calendar modules that can be used to format dates and times.
Time intervals are floating-point numbers in seconds.
Each timestamp is expressed as the amount of time that has passed since midnight (epoch) on January 1, 1970.
The time module in Python has many functions for converting common date formats. For example, the function time.time() is used to get the current timestamp, as in the following example:
Examples (Python 2.0+)
The output of the above example is:
当前时间戳为: 1459994552.51
The timestamp unit is most suitable for date arithmetic. However, dates before 1970 cannot be represented this way. Dates too far in the future also won't work, as UNIX and Windows only support up to 2038.
What is a time tuple?
Many Python functions process time as 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 a flag to determine whether it is daylight saving time |
The above is the struct_time tuple. This structure has the following attributes:
| No. | 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 | 1 to 366 (Julian calendar) |
| 8 | tm_isdst | -1, 0, 1; -1 is a flag to determine whether it is daylight saving time |
Get current time
To convert a timestamp expressed as a floating-point number into a time tuple, simply pass the floating-point number to a function such as localtime.
Examples (Python 2.0+)
The output of the above example is:
本地时间为 : 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 various formats according to your needs, but the simplest function for obtaining a readable time format is asctime():
Examples (Python 2.0+)
The output of the above example is:
本地时间为 : Thu Apr 7 10:05:21 2016
Format date
We can use the strftime method of the time module to format dates:
time.strftime(format[, t])
Example demonstration:
Examples (Python 2.0+)
The output of the above example is:
2016-04-07 10:25:09 Thu Apr 07 10:25:09 2016 1459175064.0
Python date and time formatting symbols:
- %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 Minute (00-59)
- %S Second (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 appropriate date and time representation
- %j Day of the year (001-366)
- %p Locale's 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 Locale's appropriate date representation
- %X Locale's appropriate time representation
- %Z Name of the current time zone
- %% The % character itself
Get calendar for a month
The Calendar module has a wide range of methods for handling yearly and monthly calendars, for example, printing the calendar of a month:
Examples (Python 2.0+)
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 description |
|---|---|
| 1 | time.altzone Returns the offset in seconds of the daylight saving time (DST) region west of Greenwich. If the region is east of Greenwich, a negative value is returned (such as Western Europe, including the UK). Only available for regions where daylight saving time 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" (December 11, 2008, Tuesday, 18:07:14). |
| 3 | time.clock( ) Returns the current CPU time as a floating-point number of seconds. Used to measure the elapsed time of different programs, more useful than time.time(). |
| 4 | time.ctime([secs]) It is equivalent to asctime(localtime(secs)); when no argument is given, it is equivalent to asctime(). |
| 5 | time.gmtime([secs]) Accepts a timestamp (floating-point seconds elapsed since the epoch 1970) and returns a time tuple t in Greenwich Mean Time (GMT). Note: t.tm_isdst is always 0. |
| 6 | time.localtime([secs]) Accepts a timestamp (floating-point seconds elapsed since the epoch 1970) 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 at that time). |
| 7 | time.mktime(tupletime) Accepts a time tuple and returns a timestamp (floating-point seconds elapsed since the epoch 1970). |
| 8 | time.sleep(secs) Delays the execution of the calling thread, secs is in seconds. |
| 9 | time.strftime(fmt[,tupletime]) Accepts a time tuple and returns local time as a readable string, the format is 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 fmt. |
| 11 | time.time( ) Returns the timestamp of the current time (floating-point seconds elapsed since the epoch 1970). |
| 12 | time.tzset() Reinitializes time-related settings based on 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, Americas; <=0, most of Europe, Asia, Africa). |
| 2 | time.tzname The attribute time.tzname contains a pair of strings that differ depending on the situation, namely the local time zone name with daylight saving time and that without it. |
Calendar Module
The functions in this module are all calendar-related, for example, printing the character-based monthly calendar of a month.
Monday is the default first day of the week, and Sunday is the default last day. To change the setting, you need to call the calendar.setfirstweekday() function. 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 format for the year (year) calendar, with 3 months per row, separated by a distance of c. The daily width interval is w characters. The length of each row is 21* W+18+2* C. l is the number of lines per week. |
| 2 | calendar.firstweekday( ) Returns the setting for the current starting 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 it is a leap year, otherwise returns 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 years Y1 and Y2. |
| 5 | calendar.month(year,month,w=2,l=1) Return a multi-line string calendar for year year and month month, with a two-line title and one line per week. The daily width interval 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) Return a single-layer nested list of integers. Each sublist contains integers representing a week. Dates outside year year and month month are set to 0; days within range are represented by the day of that month, starting from 1. |
| 7 | calendar.monthrange(year,month) Return two integers. The first is the weekday date code of that month, and the second is the date code of that month. Days range from 0 (Monday) to 6 (Sunday); months from 1 to 12. |
| 8 | calendar.prcal(year,w=2,l=1,c=6) Equivalent toprint calendar.calendar(year,w=2,l=1,c=6)。 |
| 9 | calendar.prmonth(year,month,w=2,l=1) Equivalent toprint calendar.month(year,month,w=2,l=1) 。 |
| 10 | calendar.setfirstweekday(weekday) Set the starting date 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 of that moment (floating-point seconds elapsed since the 1970 epoch). |
| 12 | calendar.weekday(year,month,day) Return the date 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 dates and times include:
Other extensions