Python basic in...LOGIN
Python basic introductory tutorial
author:php.cn  update time:2022-04-18 16:14:50

Python date and time


Python programs can handle dates and times in many ways, and converting date formats is a common function.

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

The time interval is a floating point decimal in seconds.

Each timestamp is expressed as how much time has passed since midnight (epoch) on January 1, 1970.

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


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

import time; #Introduce time module

ticks = time.time()
print "The current timestamp is:", ticks

The above example output result:

The current timestamp is: 1459994552.51

The timestamp unit is most suitable for date operations. But dates before 1970 cannot be expressed in this way. Dates that are too far away won't work either, UNIX and Windows are only supported until 2038.



What is a time tuple?

Many Python functions use one element to assemble 9 groups of numbers. Processing time:

##2Day1 to 31# #345678#The above is the struct_time tuple. This structure has the following attributes:
Serial numberField Value
04 digit year2008
1 Month1 to 12
Hours0 to 23
Minutes0 to 59
Seconds0 to 61 (60 or 61 is a leap second)
The day of the week0 to 6 (0 is Monday)
The day of the year 1 to 366 (Julian calendar)
Daylight Saving Time-1, 0, 1, -1 is used to determine whether The flag for daylight saving time

Serial number0 12345678

Get the current time

Convert from the time method that returns a floating point number to a time tuple, just pass the floating point number to a function such as localtime.

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

import time

localtime = time. localtime(time.time())
print "The local time is :", localtime

The above example output result:

The local time 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 to get a readable time pattern is asctime():

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

import time

localtime = time.asctime( time.localtime(time.time() ) )
print "The local time is:", localtime
The above example output result:

The local time is: Thu Apr 7 10:05:21 2016

Format date

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

time.strftime(format[ , t])
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import time

# Formatted to 2016-03 -20 11:45:39 Format
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

# Formatted into Sat Mar 28 22:24:24 2016Form
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())

# Convert the 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"))
Output result of the above example:

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

Time and date formatting symbols in python:

  • %y two-digit year representation (00-99)

  • %Y Four-digit year represents (000-9999)

  • %m month (01-12)

  • %d day in the month (0-31)

  • %H 24-hour hour (0-23)

  • ##%I 12-hour hour (01 -12)

  • %M minutes (00=59)

  • ##%S seconds (00-59)
  • %a Local simplified week name
  • %A Local complete week name
  • %b Local simplified month name
  • %B The local complete month name
  • %c The local corresponding date representation and time representation
  • %j Day within the year (001-366)
  • %p Equivalent of local A.M. or P.M.
  • %U Year The number of weeks in (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 in the year (00-53) Monday is the beginning of the week
  • %x The corresponding local date representation
  • %X The corresponding local time representation
  • %Z The name of the current time zone
  • %% The % number itself
Get the calendar of a certain month

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

# !/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 above example output results:

The following outputs the calendar for January 2016:
January 2016
Mo Tu We Th Fr Sa Su
1 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 time format conversion:

AttributeValue
tm_year2008
tm_mon1 to 12
tm_mday1 to 31
tm_hour0 to 23
tm_min0 to 59
tm_sec 0 to 61 (60 or 61 is a leap second)
tm_wday0 to 6 (0 is Monday )
tm_yday1 to 366 (Julian calendar)
tm_isdst-1, 0, 1, -1 is the flag to determine whether it is daylight saving time
Serial numberFunction and description
1time.altzone
Returns the offset of the daylight saving time area west of Greenwich Number of seconds. Negative values ​​are returned if the area is east of Greenwich (such as Western Europe, including the UK). Available only in regions where daylight saving time is enabled.
2time.asctime([tupletime])
Accepts a time tuple and returns a readable form of "Tue Dec 11 18:07: 14 2008" (Tuesday, December 11, 2008 18:07:14) is a 24-character string.
3time.clock( )
Returns the current CPU time in seconds calculated as a floating point number. It is used to measure the time consumption of different programs and is more useful than time.time().
4time.ctime([secs])
The function is equivalent to asctime(localtime(secs)). No parameters are given, which is equivalent to asctime()
5time.gmtime([secs])
Receives the timeout (the number of floating point seconds elapsed since the 1970 epoch) and returns Greenwich astronomical time The time tuple under t. Note: t.tm_isdst is always 0
6time.localtime([secs])
Receive time (floating point seconds elapsed after 1970 epoch number) and returns the time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether the local time is daylight saving time).
7time.mktime(tupletime)
Accepts a time tuple and returns the timeout (the number of floating point seconds elapsed since epoch 1970).
8time.sleep(secs)
Delay the running of the calling thread, secs refers to the number of seconds.
9time.strftime(fmt[,tupletime])
Receives a time tuple and returns the local time represented as a readable string, The format is determined by fmt.
10time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
According to The format of fmt parses a time string into a time tuple.
11time.time( )
Returns the timestamp of the current time (the number of floating-point seconds elapsed since epoch 1970).
12time.tzset()
Reinitialize time-related settings according to the environment variable TZ.

The Time module contains the following two very important attributes:

Serial NumberAttribute And description
1time.timezone
The property time.timezone is the local time zone (without daylight saving time) distance from Greenwich Offset seconds (>0, Americas; <=0 most of Europe, Asia, Africa).
2time.tzname
The attribute time.tzname contains a pair of strings that vary depending on the situation, namely The local time zone name with and without daylight saving time.


Calendar module

The functions of this module are all calendar-related, such as printing the character calendar of a certain month.

Monday is the default first day of the week, and Sunday is the default last day. To change the settings, you need to call the calendar.setfirstweekday() function. The module contains the following built-in functions:

101112
Serial numberFunction and description
1calendar.calendar(year,w=2,l=1,c=6)
Returns a year calendar in multi-line string format, with 3 months per line, and the interval is c. Daily width interval is w characters. The length of each line is 21* W+18+2* C. l is the number of lines per week.
2calendar.firstweekday( )
Returns the setting of the current weekly starting day. By default, 0 is returned when the caendar module is first loaded, which is Monday.
3calendar.isleap(year)
returns True if it is a leap year, otherwise false.
4calendar.leapdays(y1,y2)
Returns the total number of leap years between Y1 and Y2.
5calendar.month(year,month,w=2,l=1)
Returns a multi-line string The calendar format is year and month, with two rows of titles and one row for each week. Daily width interval is w characters. The length of each line is 7* w+6. l is the number of lines per week.
6calendar.monthcalendar(year,month)
Returns a single-level nested list of integers. Each sublist holds an integer representing a week. Dates outside Year, month, and month are all set to 0; days within the range are represented by the day of the month, starting from 1.
7calendar.monthrange(year,month)
Returns two integers. The first is the date code of the day of the week of the month, and the second is the day code of the month. Days range from 0 (Monday) to 6 (Sunday); months range from 1 to 12.
8calendar.prcal(year,w=2,l=1,c=6)
is 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).
calendar.setfirstweekday(weekday)Set the starting day code of each week. 0 (Monday) to 6 (Sunday).
calendar.timegm(tupletime)The opposite of time.gmtime: accepts a time tuple form and returns the time The time of day (the number of floating point seconds elapsed since the 1970 epoch).
calendar.weekday(year,month,day)Returns the date code of the given date. 0 (Monday) to 6 (Sunday). The months are 1 (January) to 12 (December).


Other related modules and functions

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

  • datetime module

  • pytz module

  • dateutil module