Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python date and time


May 10, 2021 Python2


Table of contents


Python 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.

The interval is a small number of floating points in seconds.

Each timestamp is expressed in terms of how long it has been since midnight (calendar) on January 1, 1970.

There are many functions under Python's time module that convert common date formats. As the function time.time() is used to get the current timestamp, the following example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time;  # 引入time模块

ticks = time.time()
print "当前时间戳为:", ticks

The above example output results:

当前时间戳为: 1459994552.51

Timestamp units are best suited for date operations. B ut the dates before 1970 cannot be expressed in this way. Too distant a date, UNIX and Windows only support until 2038.


What is a time group?

Many Python functions process time with 9 sets of numbers assembled in one meta:

Serial number Field Value
0 4-digit year 2008
1 Month 1 to 12
2 Day 1 to 31
3 Hours 0 to 23
4 Minutes
5 Seconds 0 to 61 (60 or 61 is a leap second)
6 The first day of the week 0 to 6 (0 is Monday)
7 The first few days of the year 1 to 366 (Julian calendar)
8 Daylight saving time -1, 0, 1, -1 is the flag that determines whether to be daylight saving time

The above is struct_time the two metagroups. This structure has the following properties:

Serial number 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 is a leap second)
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 the flag that determines whether to be daylight saving time


Gets the current time

Switch from the time drop that returns floats to the time group, as long as the floats are passed to a function such as localtime.

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time

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

The above example output results:

本地时间为 : 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)


Gets the time it was formatted

You can choose from a variety of formats depending on your needs, but the simplest function to get readable time patterns is asctime():

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time

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

The above example output results:

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

Format the date

We can format the date using the strftime method of the time module:

time.strftime(format[, t])

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import time

# 格式化成2016-03-20 11:45:39形式

print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 

# 格式化成Sat Mar 28 22:24:24 2016形式

print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 

  

# 将格式字符串转换为时间戳

a = "Sat Mar 28 22:24:24 2016"

print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

The above example output results:



Time date formatting symbol in Python:

%y Two-digit year (00-99)

%Y four-digit year (000-9999)

%m month (01-12)

One day in %d month (0-31)

%H 24 hours (0-23)

%I 1 2 hours (01-12)

%M minutes (00 s 59)

%S Seconds (00-59)

%a Local simplified week name

%A local full week name

%b Local simplified month name

%B Local full month name

%c Local corresponding date and time represents

%j Day of the Year (001-366)

%p Local A.M. or P.M. equivalent

%U The number of weeks of the year (00-53) Sunday is the beginning of the week

%w week (0-6), Sunday is the beginning of the week

%W The number of weeks of the year (00-53) Monday is the beginning of the week

%x locally represented by the corresponding date

%X is locally represented by the appropriate time

The name of the current time zone for %Z

%% % sign itself


Get a calendar for a month

The Calendar module has a wide range of methods for working with annual and monthly calendars, such as printing monthly calendars for a month:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import calendar

cal = calendar.month(2016, 1)
print "以下输出2016年1月份的日历:"
print cal;

The above example output results:

以下输出20161月份的日历:
    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 in the time-processing phase and in the conversion time format:

Serial number Functions and descriptions
1 time.altzone
Returns the number of offset seconds in the daylight saving time area west of Greenwich. I f the region returns a negative value in greenwich East (e.g. Western Europe, including the United Kingdom). Enable regions for daylight saving time to use.
2 time.asctime([tupletime])
Accept the time tudal and return a 24-character string in readable form "Tue Dec 11 18:07:14 2008" (Tuesday, December 11, 2008 18:07:14).
3 time.clock( )
The number of seconds calculated for floating points returns the current CPU time. It is more useful to measure the time-consuming time of different programs than time.time().
4 time.ctime([secs])
The effect is equivalent to asctime (localtime), and the failure to give parameters is equivalent to asctime()
5 time.gmtime([secs])
The receive time drops (floating-point seconds passed after the 1970 era) and returns to the time cell t at Greenwich Astronomical Time. Note: t.tm_isdst is always 0
6 time.localtime([secs])
The receive time drops (floating-point seconds passed after the 1970 era) and returns to the time cell t (t.tm_isdst is desirable 0 or 1 at local time, depending on whether the local time is daylight saving time at the time).
7 time.mktime(tupletime)
Accept the time group and return the time drop (the floating point seconds passed after the 1970 era).
8 time.sleep(secs)
Delay the operation of the calling thread, secs refers to the number of seconds.
9 time.strftime(fmt[,tupletime])
Receives local time in time yuans and returns local time in readable strings, the format of which is determined by fmt.
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
Resolve a time string to a time group based on the format of fmt.
11 time.time( )
Returns the timestamp of the current time (the number of floating-point seconds passed after the 1970 era).
12 time.tzset()
Re-initialize time-related settings based on the environment variable TZ.

The Time module contains two very important properties:

Serial number Properties and descriptions
1 time.timezone
The property time.timezone is the number of seconds that the local time zone (daylight saving time is not started) from Greenwich . most of Europe, Asia, Africa).
2 time.tzname
The property time.tzname contains a pair of strings that vary depending on the situation, namely, the local time zone name with daylight saving time, and the one without it.


Calendar module

The functions of this module are calendar-related, such as printing a month's character calendar.

Monday is the default first day of the week, and Sunday is the default last day. C hanging the settings requires calling the calendar.setfirstweekday() function. The module contains the following built-in functions:

Serial number Functions and descriptions
1 calendar.calendar(year,w=2,l=1,c=6)
Returns a year annual calendar in a multi-line string format, three months and one line, at an interval of c. T he daily width interval is w character. T he length of each row is 21 x W . l is the number of rows per week.
2 calendar.firstweekday( )
Returns the settings for the current weekly start date. By default, 0 is returned the first time the calendar module is loaded, monday.
3 calendar.isleap(year)
True is returned for leap years, otherwise false.
4 calendar.leapdays(y1,y2)
Returns the total number of leap years between Y1 and Y2 years.
5 calendar.month(year,month,w=2,l=1)
Returns a multi-line string format for the year's month calendar, two lines of headings, one line a week. T he daily width interval is w character. T he length of each row is 7 x w. 6. l is the number of rows per week.
6 calendar.monthcalendar(year,month)
Returns a single-layer nested list of integers. E ach sublist mount represents an integer for a week. T he dates outside the month of year month are set to 0; The days in the range are from the first days of the month, starting from 1.
7 calendar.monthrange(year,month)
Returns two integers. T he first is the date code for the day of the week of the month, and the second is the date code for that month. F rom 0 (Monday) to 6 (Sunday); Months from 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6)
Equivalent to print calendar.calendar (year, w, l, c).
9 calendar.prmonth(year,month,w=2,l=1)
Equivalent to print calendar.calendar (year, w, l, c).
10 calendar.setfirstweekday(weekday)
Set the start date code for each week. 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
In contrast to time.gmtime: accept a time group form that returns the time of the moment (the floating-point seconds passed after the 1970 era).
12 calendar.weekday(year,month,day)
Returns 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 the Python species, other modules that process dates and times are: