Latest web development tutorials

Python3 date and time

Python programs can handle dates and times in many ways, the conversion date format is a common feature.

Python provides a time and calendar module can be used to format dates and times.

Interval is in seconds floating point decimals.

Each time stamps are in since January 1, 1970 at midnight (epoch) after how long to express.

Under Python's time module has a number of functions can be converted to common date format. Such as a function time.time () is used to obtain the current time stamp following examples:

#!/usr/bin/python3

import time;  # 引入time模块

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

Examples of the above output:

当前时间戳为: 1459996086.7115328

Timestamp unit is best suited to do date arithmetic. But before 1970 as the date can not be expressed. Nor too distant date, UNIX, and Windows only supports up to 2038.



What is the time tuple?

Many Python function with one yuan assembled set of digital processing time of 9:

No. Field value
0 4-Digit Year 2008
1 month 1-12
2 day 1-31
3 hour 0-23
4 minute 0-59
5 second 0-61 (60 or 61 leap seconds)
6 The first few days of the week 0-6 (0 is Monday)
7 The first few days of the year 1-366 (Julian)
8 summer time -1, 0, 1, -1 banner decide whether daylight saving time

Above is struct_time tuple. This structure has the following properties:

No. Attributes value
0 tm_year 2008
1 tm_mon 1-12
2 tm_mday 1-31
3 tm_hour 0-23
4 tm_min 0-59
5 tm_sec 0-61 (60 or 61 leap seconds)
6 tm_wday 0-6 (0 is Monday)
7 tm_yday 1-366 (Julian)
8 tm_isdst -1, 0, 1, -1 banner decide whether daylight saving time


Get current time

Tuple conversion from floating-point return timestamps way to the time, as long as the float passed to functions like localtime.

#!/usr/bin/python3

import time

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

Examples of the above 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 select a variety of formats according to the needs, but the easiest to obtain readable time mode function is asctime ():

#!/usr/bin/python3

import time

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

Examples of the above output:

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

Date Format

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

time.strftime(format[, t])
#!/usr/bin/python3

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")))

Examples of the above output:

2016-04-07 10:29:46
Thu Apr 07 10:29:46 2016
1459175064.0

python, date and time formatting symbols:

  • % Y denote two-digit year (00-99)
  • % Y represents a four-digit year (000-9999)
  • % M month (01-12)
  • Within% d month of the day (0-31)
  • % H 24-hour clock hours (0-23)
  • % I 12 hour clock hours (01-12)
  • % M number (00 = 59) minutes
  • % S seconds (00-59)
  • % A week simplify local name
  • Local% A full weekday name
  • % B local simplify month name
  • % B full month name locally
  • % C local date corresponding representation and time representation
  • % J day of the year (001-366)
  • % P AM or PM local equivalent character
  • The% U several times a year (00-53) for the week beginning Sunday week
  • % W week (0-6), Sunday is the beginning of the week
  • % W of the year number (00-53) for the week beginning Monday week
  • % X corresponding local date representation
  • % X corresponding local time representation
  • Name% Z current time zone
  • %%% Number itself

Get a calendar month

Calendar module has a wide range of methods used to process calendar and the calendar, such as printing a calendar month:

#!/usr/bin/python3

import calendar

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

Examples of the above output:

以下输出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

Time module contains the following built-in functions, both the time to deal with, but also the conversion time format:

No. Function and description Examples
1 time.altzone
Back in West Greenwich area of ​​daylight saving time offset in seconds. If the area is returned in the Eastern Greenwich negative value (such as Western Europe, including the UK). Enable to use Daylight Saving Time area right.

The following example shows altzone () function to use:

>>> import time
>>> print ("time.altzone %d " % time.altzone)
time.altzone -28800 
2 time.asctime ([tupletime])
Time to accept and return a tuple readable form as a string "Tue Dec 11 18:07:14 2008" (December 11, 2008 Tuesday 18:07:14) 24 characters.

The following example shows asctime () function to use:

>>> 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 ()
The number of seconds to return the current floating-point computations of CPU time. Different procedures used to measure the time-consuming than time.time () more useful.
Examples
4 time.ctime ([secs])
Acts asctime (localtime (secs)), is not equivalent to the parameter asctime ()

The following example shows ctime () function to use:

>>> import time
>>> print ("time.ctime() : %s" % time.ctime())
time.ctime() : Thu Apr  7 10:51:58 2016
5 time.gmtime ([secs])
Reception timestamps (1970 era after the floating-point number of seconds) and return time at Greenwich astronomical time tuple t. NOTE: t.tm_isdst always 0

The following example shows gmtime () function to use:

>>> 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]
Reception timestamps (1970 era after the floating-point number of seconds) and return to the local time at the time of the tuple t (t.tm_isdst desirability 0 or 1, the local time is not dependent on daylight saving time).

The following example shows the localtime () function to use:

>>> 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)
Time to accept and return a tuple timestamps (1970 era after the floating-point number of seconds).
Examples
8 time.sleep (secs)
Postpone the calling thread is running, secs number of seconds.

The following example shows the sleep () function to use:

#!/usr/bin/python3
import time

print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())
9 time.strftime (fmt [, tupletime])
Receiving a time-tuple and returns a string representation of the local time in a readable format determined by fmt.

The following example shows strftime () function to use:

>>> 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')
According to a time fmt format strings are interpreted as a time tuple.

The following example shows strftime () function to use:

>>> 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 timestamp (epoch 1970 after the floating-point number of seconds).

The following example shows the time () function to use:

>>> import time
>>> print(time.time())
1459999336.1963577
12 time.tzset ()
According to the environmental variable TZ re-initialization settings.
Examples

Time module contains the following two very important properties:

No. Attributes and description
1 time.timezone
Property time.timezone local time zone (not started daylight saving time) offset from Greenwich seconds (> 0, the Americas; <= 0 most of Europe, Asia, Africa).
2 time.tzname
Time.tzname property includes a pair of depending on the circumstances and different strings, respectively, the name of the local time zone with daylight saving time, and without the band.


Calendar (Calendar) module

This module functions are related to the calendar, such as printing a character calendar month.

Monday is the default first day of week, Sunday is the last day of default. Change the setting to be called calendar.setfirstweekday () function. 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 calendar year in string format, 3 months line spacing distance c. Daily interval width w characters. Each line length is 21 * W + 18 + 2 * C. l is the number of rows per week.
2 calendar.firstweekday ()
Back Set start date of the current week. By default, when you first load caendar module returns 0, ie Monday.
3 calendar.isleap (year)
It is a leap year returns True, otherwise false.
4 calendar.leapdays (y1, y2)
Back in the Y1, Y2 total number of leap years between.
5 calendar.month (year, month, w = 2, l = 1)
Returns a multi-line strings in the format year-month calendar month, two lines of headings week line. Daily interval width w characters. The length of each line is 7 * w + 6. l is the number of lines per week.
6 calendar.monthcalendar (year, month)
It returns an integer nested lists monolayer. Each sub-list of integer load a week's representative. Date Year month in month outside are set to 0; day range by the first few days of the month, he said starting from 1.
7 calendar.monthrange (year, month)
Returns two integers. The first week of the month is the date code, and the second is the month of the date code. From day 0 (Monday) through 6 (Sunday); from January 1-12.
8 calendar.prcal (year, w = 2, l = 1, c = 6)
Equivalent print calendar.calendar (year, w, l, c).
9 calendar.prmonth (year, month, w = 2, l = 1)
Equivalent print calendar.calendar (year, w, l, c).
10 calendar.setfirstweekday (weekday)
Setting the week starting date code. 0 (Monday) through 6 (Sunday).
11 calendar.timegm (tupletime)
And time.gmtime opposite: to accept the form of a time tuple, returns the time timestamps (1970 era after the floating-point number of seconds).
12 calendar.weekday (year, month, day)
Returns the date of the date code. 0 (Monday) through 6 (Sunday). 1 month (January) to 12 (December).


Other related modules and functions

In Python, dates and times of other processing modules are: