Python date and time processing module (date and datetime)

Source: Internet
Author: User
This article mainly introduces the date and time processing module (date and datetime) of Python. I think it is quite good for you to make a reference. Let's take a look at it with Xiaobian. Preface

In development, we often need dates and times, such:

  • Output as log information

  • Calculate the execution time of a function.

  • Name a log file by date

  • Record or display the publishing or modification time of an article

  • Others

Python provides multiple built-in modules for date and time operations: time module, datetime module, and calendar module. The time module is implemented by calling the C library, so some methods may not be called on some platforms. However, most of the interfaces provided by the time module are basically the same as those provided by the C standard library time. h. Compared with the time module, the datetime module provides more intuitive and easy-to-use interfaces and more powerful functions.

I. interpretation of related terms

  • UTC time Coordinated Universal Time, the world coordination time, also known as Greenwich Mean astronomical Time, the world standard time. The local time of each time zone corresponds to UTC time. the time in the east N zone is N hours earlier than the UTC time. Therefore, UTC time + N hours is the local time in the east N zone; the time in the West N zone is N hours later than the UTC time, that is, UTC time-N hours is the local time in the West N zone; China is in the East 8 zone, therefore, it is 8 hours earlier than UTC time and can be expressed in UTC + 8.

  • Epoch time indicates the start point of the time. it is a specific time. The value of this time point is not the same on different platforms. for Unix, epoch time is 00:00:00 UTC.

  • Timestamp (timestamp) is also known as Unix time or POSIX time. it is a time representation of the number of milliseconds that have elapsed since 00:00:00 GMT, January 1, January 1, 1970, the value is of the float type. However, in some programming languages, the related methods return the number of seconds (in this case, Python). please refer to the instructions in the method documentation. Note that the timestamp is a difference value, and its value is irrelevant to the time zone.

II. time representation

Common time representation:

  • Timestamp

  • Formatted time string

There are other time representations in Python:

  • Time. struct_time of the time module

  • Datetime class of the datetime module

The datetime class of the datetime module will be explained in detail below. here we will briefly describe time. struct_time.

Time. struct_time contains the following attributes:


Subscript/index Attribute name Description
0 Tm_year Year, such as 2017
1 Tm_mon Month, value range: [1, 12]
2 Tm_mday The day of the month. value range: [1-31]
3 Tm_hour Hour, value range: [0-23]
4 Tm_min Minutes, value range: [0, 59]
5 Tm_sec Second, value range: [0, 61]
6 Tm_wday The day of a week. The value range is [0-6]. 0 indicates Monday.
7 Tm_yday The day of the year. value range: [1, 1,366].
8 Tm_isdst Optional values: 0, 1, or-1

You can obtain attribute values in two ways:

  • It can be used as a special sequence of ordered immutable to obtain the values of each element through subscript/index, such as t [0]

  • You can also use the. attribute name to obtain the values of each element, such as t. tm_year.

It must be noted that all attributes of the struct_time instance are read-only and cannot be modified.

III. time module

The time module is mainly used for time access and conversion. This module provides various time-related functions.

1. function list


Method/attribute Description
Time. altzone Returns the time difference from utc time, in seconds (the value of the western region is positive, and the value of the eastern region is negative ). It indicates the offset of the local DST time zone, which is used only when daylight is not 0.
Time. clock () Returns the number of seconds (excluding sleep time) of the processor consumed by the current process. The value is decimal. in Python3.3, this method is changed to time. process_time ()
Time. asctime ([t]) Converts a time string in the form of tuple or struct_time (which can be obtained through the gmtime () and localtime () methods) to a 24-character time string in the format: "Fri Aug 19 11:14:16 2016 ". If parameter t is not provided, the return value of localtime () is used as the parameter.
Time. ctime ([secs]) The same function is used to convert a timestamp in seconds to a string that represents the current local time. If the secs parameter is not provided or the value is None, the return value of the time () method is used as the default value. Ctime (secs) is equivalent to asctime (localtime (secs ))
Time. time () Returns the timestamp (the number of seconds that have elapsed since 0:00:00)
Time. localtime ([secs]) Returns the struct_time object of the local time corresponding to the specified timestamp (internal properties can be referenced either by subscript or by. attribute name ).
Time. localtime (time. time () + n * 3600) Returns the struct_time object format (similar to crontab) of the local time after n hours)
Time. gmtime ([secs]) Returns the struct_time object format of the utc time corresponding to the specified timestamp (8 hours time difference from the current local time)
Time. gmtime (time. time () + n * 3600) Returns the struct_time object of utc time after n hours (internal attributes can be referenced by. attribute names ).
Time. strptime (time_str, time_format_str) Converts a time string to a struct_time time object, for example, time. strptime ('2017-01-13 ',' % Y-% m-% d % H: % M ')
Time. mktime (struct_time_instance) Converts a struct_time object instance to a timestamp.
Time. strftime (time_format_str, struct_time_instance) Converts a struct_time object instance to a string.

2. exercise

Obtain the timestamp format

>>> time.time()1486188022.862

Get the time in struct_time format

>>> time.localtime()time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=2, tm_sec=34, tm_wday=5, tm_yday=35, tm_isdst=0)>>> time.gmtime()time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=6, tm_min=2, tm_sec=56, tm_wday=5, tm_yday=35, tm_isdst=0)

Obtain the time of string format

>>> time.ctime()'Sat Feb 04 14:06:42 2017'>>> time.asctime()'Sat Feb 04 14:06:47 2017'

Time stamp format to struct_time format

>>> t1 = time.time()>>> print(t1)1486188476.9>>> t2 = time.localtime(t1)>>> print(t2)time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=7, tm_sec=56, tm_wday=5, tm_yday=35, tm_isdst=0)>>> t3 = time.gmtime(t1)>>> print(t3)time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=6, tm_min=7, tm_sec=56, tm_wday=5, tm_yday=35, tm_isdst=0)>>>

String format to struct_time format Time

>>> time.strptime('Sat Feb 04 14:06:42 2017')time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=6, tm_sec=42, tm_wday=5, tm_yday=35, tm_isdst=-1)>>> time.strptime('Sat Feb 04 14:06:42 2017', '%a %b %d %H:%M:%S %Y')time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=6, tm_sec=42, tm_wday=5, tm_yday=35, tm_isdst=-1)>>> time.strptime('2017-02-04 14:12', '%Y-%m-%d %H:%M')time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)>>> time.strptime('2017/02/04 14:12', '%Y/%m/%d %H:%M')time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)>>> time.strptime('201702041412', '%Y%m%d%H%M')time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=14, tm_min=12, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)

Struct_time format to string format Time

>>> Time. strftime ('% Y-% m-% d % H: % M', time. localtime () '2017-02-04 'struct _ time format to timestamp format time >>> time. mktime (time. localtime () 1486189282.0

3. time format conversion

Although the time in the timestamp format and the time in the string format can be converted using the ctime ([secs]) method, the string format is not suitable for China's national conditions. Therefore, on the whole, they cannot be directly converted and must use struct_time as the intermediary. the conversion relationship is as follows:

object date datetime time timedelta tzinfo timezone

2. constants defined in the datetime module


Constant name Description
Datetime. MINYEAR The minimum value of the year allowed by the datetime. date or datetime. datetime object. The value is 1.
Datetime. MAXYEAR The maximum value of the year allowed by the datetime. date or datetime. datetime object, only 9999

3. datetime. date class

Definition of datetime. date class

class datetime.date(year, month, day)

Year, month, and day are both mandatory parameters. the value range of each parameter is:


Parameter name Value range
Year [MINYEAR, MAXYEAR]
Month [1, 12]
Day [1, number of days in the month of the specified year]

Class methods and attributes


Class method/attribute name Description
Date. max The maximum date that a date object can represent: 9999-12-31
Date. min Minimum log that the date object can represent: 00001-01-01
Date. resoluation The minimum unit of the date object: Day
Date. today () Returns a date object that represents the current local date.
Date. fromtimestamp (timestamp) Returns a date object based on the specified timestamp.

Object methods and attributes


Object method/attribute name Description
D. year Year
D. month Month
D. day Day
D. replace (year [, month [, day]) Generate and return a new date object. The original date object remains unchanged.
D. timetuple () Returns the time. struct_time object corresponding to the date.
D. toordinal () Returns the number of days since 0001-01-01.
D. weekday () Returns the day of the week. [0, 6]. 0 indicates Monday.
D. isoweekday () The return date is the day of the week. [1, 7], 1 indicates Monday.
D. isocalendar () Returns a tuple in the format of year, weekday, and isoweekday)
D. isoformat () Returns a date string in 'yyyy-MM-DD 'format
D. strftime (format) Returns the date string in the specified format, which is the same as the strftime (format, struct_time) function of the time module.

Instance

>>> import time>>> from datetime import date>>>>>> date.maxdatetime.date(9999, 12, 31)>>> date.mindatetime.date(1, 1, 1)>>> date.resolutiondatetime.timedelta(1)>>> date.today()datetime.date(2017, 2, 4)>>> date.fromtimestamp(time.time())datetime.date(2017, 2, 4)>>>>>> d = date.today()>>> d.year2017>>> d.month2>>> d.day4>>> d.replace(2016)datetime.date(2016, 2, 4)>>> d.replace(2016, 3)>>> d.replace(2016, 3, 2)datetime.date(2016, 3, 2)>>> d.timetuple()time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)>>> d.toordinal()736364>>> d.weekday()5>>> d.isoweekday()6>>> d.isocalendar()(2017, 5, 6)>>> d.isoformat()'2017-02-04'>>> d.ctime()'Sat Feb 4 00:00:00 2017'>>> d.strftime('%Y/%m/%d')'2017/02/04'

4. datetime. time class

Definition of time class

class datetime.time(hour, [minute[, second, [microsecond[, tzinfo]]]])

Hour is a required parameter, and others are optional parameters. The value range of each parameter is:


Parameter name Value range
Hour [0, 23]
Minute [0, 59]
Second [0, 59]
Microsecond [0, 1, 1000000]
Tzinfo A subclass object of tzinfo, such as an instance of the timezone class.

Class methods and attributes


Class method/attribute name Description
Time. max Maximum time that the time class can represent: time (23, 59, 59,999 999)
Time. min Minimum time that the time class can represent: time (0, 0, 0, 0)
Time. resolution The minimum unit of time, that is, the minimum difference between two different times: 1 microsecond

Object methods and attributes


Object method/attribute name Description
T. hour Hour
T. minute Minute
T. second Seconds
T. microsecond Microseconds
T. tzinfo Return the tzinfo object passed to the time constructor. If this parameter is not provided, None is returned.
T. replace (hour [, minute [, second [, microsecond [, tzinfo]) Generate and return a new time object. the original time object remains unchanged.
T. isoformat () Returns a time string in the format of 'hh: MM: SS. % f '.
T. strftime () Returns the time string in the specified format, which is the same as the strftime (format, struct_time) function of the time module.

Instance

>>> from datetime import time>>>>>> time.maxdatetime.time(23, 59, 59, 999999)>>> time.mindatetime.time(0, 0)>>> time.resolutiondatetime.timedelta(0, 0, 1)>>>>>> t = time(20, 5, 40, 8888)>>> t.hour20>>> t.minute5>>> t.second40>>> t.microsecond8888>>> t.tzinfo>>>>>> t.replace(21)datetime.time(21, 5, 40, 8888)>>> t.isoformat()'20:05:40.008888'>>> t.strftime('%H%M%S')'200540'>>> t.strftime('%H%M%S.%f')'200540.008888'

5. datetime. datetime class

Definition of datetime class


The code is as follows:


Class datetime. datetime (year, month, day, hour = 0, minute = 0, second = 0, microsecond = 0, tzinfo = None)

Year, month, and day are required parameters. tzinfo can be an instance of the None or tzinfo subclass.

The value range of each parameter is:


Parameter name Value range
Year [MINYEAR, MAXYEAR]
Month [1, 12]
Day [1, number of days in the month of the specified year]
Hour [0, 23]
Minute [0, 59]
Second [0, 59]
Microsecond [0, 1, 1000000]
Tzinfo A subclass object of tzinfo, such as an instance of the timezone class.

If a parameter is out of these ranges, ValueError may occur.

Class methods and attributes


Class method/attribute name Description
Datetime. today () Returns a datetime object that represents the current date and time.
Datetime. now ([tz]) Returns the datetime object of the specified time zone, and returns the same result if the tz parameter is not specified.
Datetime. utcnow () Returns the datetime object of the current utc date and time.
Datetime. fromtimestamp (timestamp [, tz]) Creates a datetime object based on the specified timestamp.
Datetime. utcfromtimestamp (timestamp) Creates a datetime object based on the specified timestamp.
Datetime. combine (date, time) Integrates the specified date and time objects into a datetime object.
Datetime. strptime (date_str, format) Converts a time string to a datetime object.

Object methods and attributes


Object method/attribute name Description
Dt. year, dt. month, dt. day Year, month, and day
Dt. hour, dt. minute, dt. second Hour, minute, second
Dt. microsecond, dt. tzinfo Microsecond, time zone information
Dt. date () Obtain the date object corresponding to the datetime object
Dt. time () Obtains the time object corresponding to the datetime object. The value of tzinfo is None.
Dt. timetz () Obtains the time object corresponding to the datetime object. tzinfo is the same as the tzinfo of The datetime object.
Dt. replace ([year [, month [, day [, hour [, minute [, second [, microsecond [, tzinfo]) Generate and return a new datetime object. if none of the parameters are specified, return an object with the same as the original datetime object
Dt. timetuple () Returns the tuple corresponding to the datetime object (excluding tzinfo)
Dt. utctimetuple () Returns the tuple (excluding tzinfo) of the utc time corresponding to the datetime object)
Dt. toordinal () Same date object
Dt. weekday () Same date object
Dt. isocalendar () Exclusive with date
Dt. isoformat ([sep]) Returns '% Y-% m-% d
Dt. ctime () It is equivalent to the time. ctime (time. mktime (d. timetuple () of the time module ()))
Dt. strftime (format) Returns the time string in the specified format.

Instance

>>> from datetime import datetime, timezone>>>>>> datetime.today()datetime.datetime(2017, 2, 4, 20, 44, 40, 556318)>>> datetime.now()datetime.datetime(2017, 2, 4, 20, 44, 56, 572615)>>> datetime.now(timezone.utc)datetime.datetime(2017, 2, 4, 12, 45, 22, 881694, tzinfo=datetime.timezone.utc)>>> datetime.utcnow()datetime.datetime(2017, 2, 4, 12, 45, 52, 812508)>>> import time>>> datetime.fromtimestamp(time.time())datetime.datetime(2017, 2, 4, 20, 46, 41, 97578)>>> datetime.utcfromtimestamp(time.time())datetime.datetime(2017, 2, 4, 12, 46, 56, 989413)>>> datetime.combine(date(2017, 2, 4), t)datetime.datetime(2017, 2, 4, 20, 5, 40, 8888)>>> datetime.strptime('2017/02/04 20:49', '%Y/%m/%d %H:%M')datetime.datetime(2017, 2, 4, 20, 49)>>> dt = datetime.now()>>> dtdatetime.datetime(2017, 2, 4, 20, 57, 0, 621378)>>> dt.year2017>>> dt.month2>>> dt.day4>>> dt.hour20>>> dt.minute57>>> dt.second0>>> dt.microsecond621378>>> dt.tzinfo>>> dt.timestamp()1486213020.621378>>> dt.date()datetime.date(2017, 2, 4)>>> dt.time()datetime.time(20, 57, 0, 621378)>>> dt.timetz()datetime.time(20, 57, 0, 621378)>>> dt.replace()datetime.datetime(2017, 2, 4, 20, 57, 0, 621378)>>> dt.replace(2016)datetime.datetime(2016, 2, 4, 20, 57, 0, 621378)>>> dt.timetuple()time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=-1)>>> dt.utctimetuple()time.struct_time(tm_year=2017, tm_mon=2, tm_mday=4, tm_hour=20, tm_min=57, tm_sec=0, tm_wday=5, tm_yday=35, tm_isdst=0)>>> dt.toordinal()736364>>> dt.weekday()5>>> dt.isocalendar()(2017, 5, 6)>>> dt.isoformat()'2017-02-04T20:57:00.621378'>>> dt.isoformat(sep='/')'2017-02-04/20:57:00.621378'>>> dt.isoformat(sep=' ')'2017-02-04 20:57:00.621378'>>> dt.ctime()'Sat Feb 4 20:57:00 2017'>>> dt.strftime('%Y%m%d %H:%M:%S.%f')'20170204 20:57:00.621378'

6. use the datetime. datetime class to convert the timestamp and time string.

>>> Import datetime >>>>> datetime. timedelta (365 ). total_seconds () # total number of seconds in a year: 31536000.0> dt = datetime. datetime. now () >>> dt + datetime. timedelta (3) # datetime after 3 days. datetime (2017, 2, 8, 9, 39, 40,102 821)> dt + datetime. timedelta (-3) # datetime 3 days ago. datetime (2017, 2, 2, 9, 39, 40,102 821)> dt + datetime. timedelta (hours = 3) # datetime after 3 hours. datetime (2017, 2, 5, 12, 39, 40,102 821)> dt + datetime. timedelta (hours =-3) # datetime 3 hours ago. datetime (2017, 2, 5, 6, 39, 40,102 821)> dt + datetime. timedelta (hours = 3, seconds = 30) #3 hours 30 seconds later datetime. datetime (2017, 2, 5, 12, 40, 10,102 821)

5. time format code

The struct_time of the time module and the datetime, date, and time classes of the datetime module provide the strftime () method, which can output a time string in a specified format. The specific format consists of a series of format codes (format characters). Python finally calls the strftme () function of the C library of each platform, therefore, the platform supports a full set of format codes. for details, refer to the strftime (3) document on the platform. The following lists all the format codes required by the C standard (version 1989), which can work on all platforms that implement the standard C:

VI. Summary

When processing time in Python, is it better to use the time module or the datetime module? In my personal opinion, the datetime module can basically meet the needs, and it is indeed more convenient to use. For the time module, I only use time when getting the timestamp of the current time. the time () method, of course, can also use datetime. datetime. now (). timestamp. I think it's better to look at my habits. there is no absolute difference between good and bad.

The above is all the content of this article. I hope it will help you learn and support PHP.

For more articles about the date and time processing module (date and datetime) in Python, refer to PHP!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.