Python 3 Date and time processing module (date and datetime)

Source: Internet
Author: User
Tags epoch time instance method local time string format timedelta

Objective
Interpretation of related terms
The manifestation of time
Time Module
DateTime module
Time Format Code
Summarize
Objective

In the development work, we often need to use the date and time, such as:

Content output as log information
Calculate the execution time of a feature
Name a log file by date
Record or display the time of publication or modification of an article
Other
Python provides several built-in modules for manipulating dates and times: The time module, the DateTime module, and the Calendar module. Where the time module is implemented by invoking the C library, some methods may not be callable on some platforms, but most of the interfaces provided are basically consistent with the C standard library time.h. The interface provided by the DateTime module is more intuitive, easy to use, and more powerful than the time module.

I. Interpretation of related terms

UTC time coordinated Universal times, world co-ordination, also known as GMT, world standard Time. The UTC time corresponds to the local time of each time zone, and the East N area is n hours earlier than UTC, so the UTC time + n hours are the native times of the East N region, whereas the West n zone is n hours later than UTC, that is, UTC time-n hours is the local time of the West N region; China is in the East 8 district, so 8 hours earlier than UTC time, can be expressed as utc+8.

Epoch time is the starting point for the beginning; it is a specific time, the value of this point in different platforms is not the same, and for UNIX, epoch time is 1970-01-01 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 elapsed from 0:0 GMT January 1, 1970 to 0 seconds, with a value of type float. But some programming language related methods return the number of seconds (Python is like this), this need to look at the document description of the method. It is necessary to note that the timestamp is a difference and its value is independent of the time zone.

Second, the time expression form

The common time representation is:

Time stamp
Formatted time string
There are other time representations in Python:

Time.struct_time of the Time module
DATETIME Classes for datetime modules
The DateTime class for the DateTime module will be explained in detail below, here simply time.struct_time.

The time.struct_time contains the following properties:

Subscript/Indexed Property name Description
0 tm_year year, such as 2017
1 Tm_mon month, value range is [1, 12]
2 Tm_mday the day of the one month, the value range is [1-31]
3 Tm_hour hours, value range is [0-23]
4 tm_min minutes with a value range of [0, 59]
5 tm_sec seconds, the value range is [0, 61]
6 Tm_wday the day of the one week, the value range is [0-6],0 = Monday
7 Tm_yday The first day of the year, the value range is [1, 366]
8 TM_ISDST is daylight saving time, the desired value is: 0, 1 or-1
There are two ways to get property values:

It can be used as a special ordered immutable sequence to get the values of each element by subscript/index, e.g. T[0]
You can also get the values of individual elements, such as t.tm_year, by means of the. Property name.
It is necessary to note that the individual properties of the Struct_time instance are read-only and cannot be modified.

Three, Time module

Time modules are primarily used for temporal access and conversion, and this module provides a variety of time-related functions.

    1. List of functions

Method/Property Description
Time.altzone returns the time difference, in seconds, from UTC (The value is positive in the west side, and the value in the east is negative). It represents the offset of the local DST time zone, which is only used when daylight is not 0 o'clock.
Time.clock () returns the number of seconds (excluding sleep time) that the current process consumes for the processor, and the value is decimal; the method Python3.3 changed to Time.process_time ()
Time.asctime ([t]) converts a tuple or struct_time form of time (which can be obtained through the gmtime () and LocalTime () methods) to a 24-character time string in the form: "Fri 19 11:14:16 2016 ". If the parameter T is not provided, take the return value of localtime () as the parameter.
Time.ctime ([secs]) functions as above, converting the time of a second timestamp to a string representing the current local time. If the parameter secs is not provided or the value is None, the return value of the time () method is taken as the default value. CTime (secs) equivalent to Asctime (localtime (secs))
Time.time () returns the timestamp (number of seconds since 1970-1-1 0:00:00 to date)
Time.localtime ([secs]) returns a Struct_time object that has a local time corresponding to the specified timestamp (either by subscript or by using the. Property name to refer to the internal property) format
Time.localtime (Time.time () + N3600) Returns the Struct_time object format for local time after n hours (can be used to implement a function similar to crontab)
Time.gmtime ([secs]) returns the Struct_time object format for UTC time corresponding to the specified timestamp (8 hours with the current local time difference)
Time.gmtime (Time.time () + N
3600) Returns the Struct_time object of UTC time after n hours (you can refer to the internal property by means of the. Property name) format
Time.strptime (TIME_STR, TIME_FORMAT_STR) converts the time string to a struct_time time object, such as: Time.strptime (' 2017-01-13 17:07 ', '%Y-%m-%d%H: %M ')
Time.mktime (struct_time_instance) converts Struct_time object instances to timestamps
Time.strftime (TIME_FORMAT_STR, struct_time_instance) converts a Struct_time object instance to a string

    1. Practice

Time to get timestamp format

>> Time.time ()
1486188022.862
Get 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)
Gets the time of the string format

>> Time.ctime ()
' Sat 04 14:06:42 2017 '
>> Time.asctime ()
' Sat 04 14:06:47 2017 '
Timestamp format goto struct_time format time

>> 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 goto struct_time format time

>> time.strptime (' Sat 14:06:42 ')
Time.struct_time (tm_year=2017, tm_mon=2, tm_mday=4, tm_hour= Tm_min=6, tm_sec=42, tm_wday=5, tm_yday=35, tm_isdst=-1)
>> time.strptime (' Sat 14:06:42 ', '%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= 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= 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 14:19 '
Struct_time format to timestamp format time

>> Time.mktime (Time.localtime ())
1486189282.0

    1. Time format Conversion

Time stamp format time and string format time although can be converted through the CTime ([secs]) method, but the string format is not very suitable for Chinese conditions. Therefore, as a whole, they cannot be converted directly and need to be mediated by Struct_time, as follows:

Note: The above '%h:%m:%s ' can be replaced directly with '%x '.

D. DateTime module

The DateTime module provides classes for working with dates and times, both in a simple way and in a complex way. Although it supports date and time algorithms, its implementation focuses on providing efficient property extraction capabilities for output formatting and operation.

    1. Classes defined in a datetime module

The DateTime module defines the following classes:

Class Name Description
Datetime.date represents a date, and the commonly used attributes are: year, month, and day
Datetime.time represents time, common attributes are: hour, minute, second, microsecond
Datetime.datetime represents the date time
Datetime.timedelta represents the interval between two date, time, and DateTime instances, with a resolution (smallest unit) up to microseconds
Datetime.tzinfo the abstract base class for the time zone-related information object. They are used by the datetime and time classes to provide custom times for tuning.
Datetime.timezone New in Python 3.2, implements the class of Tzinfo abstract base class, representing a fixed offset from UTC
It is necessary to note that the objects of these classes are immutable.

The relationships between classes:

Object
Date
Datetime
Time
Timedelta
Tzinfo
TimeZone

    1. Constants defined in a datetime module

Constant Name Description
Datetime. Minyear the minimum value of the year allowed by the Datetime.date or Datetime.datetime object, with a value of 1
Datetime. Maxyear the maximum number of years allowed for a datetime.date or Datetime.datetime object, only 9999

    1. Datetime.date class

Definition of the Datetime.date class

Class Datetime.date (year, month, day)
Year, month, and day are all required parameters, and the values for each parameter range from:

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 properties

class Method/Property name Description
Date.max Date object can be represented by the maximum number of dates: 9999-12-31
Date.min the minimum log that the Date object can represent: 00001-01-01
Date.resoluation the smallest unit of date represented by the Date object: Days
Date.today () Returns a Date object that represents the current local date
Date.fromtimestamp (timestamp) Returns a Date object based on the timestamp that is set
Object Methods and properties

Object method/Property name Description
D.year year
D.month Month
D.day Day
D.replace (year[, month[, Day]) generates and returns a new Date object with the original date object unchanged
D.timetuple () returns the Time.struct_time object corresponding to the date
D.toordinal () Return date is the number of days since the beginning of 0001-01-01
D.weekday () Returns the day of the week, [0, 6],0, Monday
D.isoweekday () Return date is day of the week, [1, 7], 1 means Monday
D.isocalendar () returns a tuple in the format: (year, weekday, Isoweekday)
D.isoformat () returns a date string in ' YYYY-MM-DD ' format
D.strftime (format) returns a date string in the specified format, the same as the strftime (format, struct_time) function of the time module
Instance

>> Import Time
>> from datetime import Date
>>
>> Date.max
Datetime.date (9999, 12, 31)
>> Date.min
Datetime.date (1, 1, 1)
>> date.resolution
Datetime.timedelta (1)
>> Date.today ()
Datetime.date (2017, 2, 4)
>> Date.fromtimestamp (Time.time ())
Datetime.date (2017, 2, 4)
>>
>> d = date.today ()
>> D.year
2017
>> D.month
2
>> D.day
4
>> 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 4 00:00:00 2017 '
>> d.strftime ('%y/%m/%d ')
' 2017/02/04 '

    1. Datetime.time class

Definition of the time class

Class Datetime.time (hour, [minute[, Second, [microsecond[, Tzinfo]]])
The hour is a mandatory parameter, and the other is an optional parameter. The values for each parameter range are:

Parameter Name value range
hour [0, 23]
minute [0, 59]
Second [0, 59]
microsecond [0, 1000000]
Tzinfo a subclass of Tzinfo object, such as an instance of the TimeZone class
Class methods and properties

class Method/Property name Description
Time.max time class can be represented by the maximum duration: times (23, 59, 59, 999999)
Time.min the minimum time that can be represented by the hour class: times (0, 0, 0, 0)
The smallest unit of time.resolution time, which is the minimum difference of two different times: 1 microseconds
Object Methods and properties

Object method/Property name Description
When T.hour
T.minute min
T.second sec
T.microsecond μs
T.tzinfo returns the Tzinfo object passed to the time construction method, or None if the parameter is not given
T.replace (hour[, minute[, second[, microsecond[, Tzinfo]]]) generates and returns a new time object unchanged from the original time object
T.isoformat () returns a time string in ' hh:mm:ss.%f ' format
T.strftime () returns the time string in the specified format, same as the strftime (format, struct_time) function of the temporal module
Instance

>> from datetime import Time
>>
>> Time.max
Datetime.time (23, 59, 59, 999999)
>> Time.min
Datetime.time (0, 0)
>> time.resolution
Datetime.timedelta (0, 0, 1)
>>
>> t = time (20, 5, 40, 8888)
>> T.hour
20
>> T.minute
5
>> T.second
40
>> T.microsecond
8888
>> 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 '

  1. Datetime.datetime class

Definition of a DateTime class

Class Datetime.datetime (year, month, day, hour=0, minute=0, Second=0, Microsecond=0, Tzinfo=none)
Year, month, and day are arguments that must be passed, and tzinfo can be instances of None or tzinfo subclasses.

The values for each parameter range are:

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, 1000000]
Tzinfo a subclass of Tzinfo object, such as an instance of the TimeZone class
If a parameter exceeds these ranges, it causes a ValueError exception.

Class methods and properties

class Method/Property name Description
Datetime.today () returns a DateTime object that represents the current period date time
DateTime.Now ([TZ]) returns a DateTime object for the specified time zone datetime, if the TZ parameter is not specified the result is the same as
Datetime.utcnow () returns a DateTime object for the current UTC datetime
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) consolidates 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 properties

Object method/Property name Description
Dt.year, Dt.month, Dt.day year, month, day
Dt.hour, Dt.minute, dt.second hours, minutes, seconds
Dt.microsecond, Dt.tzinfo microseconds, time zone information
Dt.date () Gets the date object corresponding to the DateTime object
Dt.time () Gets the time object corresponding to the DateTime object, Tzinfo is None
Dt.timetz () Gets the time object corresponding to the DateTime object, tzinfo the same as the tzinfo of the DateTime object
Dt.replace ([year[, month[, day[, hour[, minute[, second[, microsecond[, Tzinfo]] []]]) generates and returns a new DateTime object, Returns an object that is the same as the original DateTime object if none of the parameters are specified
Dt.timetuple () returns the tuple corresponding to the DateTime object (excluding Tzinfo)
Dt.utctimetuple () returns a tuple of UTC time for a DateTime object (excluding Tzinfo)
Dt.toordinal () with Date object
Dt.weekday () with Date object
Dt.isocalendar () exclusive with date
Dt.isoformat ([Sep]) returns a '%y-%m-%d
Dt.ctime () equivalent to the time.ctime of the Time module (Time.mktime (D.timetuple ()))
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 (2, 4, 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, 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 ()
>> DT
Datetime.datetime (2017, 2, 4, 20, 57, 0, 621378)
>> Dt.year
2017
>> Dt.month
2
>> Dt.day
4
>> Dt.hour
20
>> Dt.minute
57
>> Dt.second
0
>> Dt.microsecond
621378
>> 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 4 20:57:00 2017 '
>> dt.strftime ('%y%m%d%h:%m:%s.%f ')
' 20170204 20:57:00.621378 '

    1. Converting timestamps and time strings using the Datetime.datetime class
    1. Datetime.timedelta class

The Timedelta object represents the difference between a different time. If you use the time module to run an arithmetic operation, it is obviously inconvenient to convert only time objects in string format and struct_time format to timestamp format, then add or subtract n seconds from the timestamp, and then convert back to struct_time format or string format. The Timedelta class provided by the DateTime module allows us to do arithmetic operations on Datetime.date, Datetime.time and Datetime.datetime objects, and the difference units between two times are more manageable.
The units of this difference can be: days, seconds, microseconds, milliseconds, minutes, hours, weeks.

Definition of the Datetime.timedelta class

Class Datetime.timedelta (Days=0, seconds=0, Microseconds=0, Milliseconds=0, hours=0, weeks=0)
All parameters are default parameters, so they are optional. The value of the parameter can be an integer or floating-point number, or it can be a positive or negative. The internal values store days, seconds, and microseconds, and all other parameters are converted to these 3 units:

1 milliseconds converted to 1000 microseconds
1 minutes to 60 seconds
1-hour conversion to 3,600 seconds
1 weeks conversion to 7 days
These 3 values are then normalized so that their representations are unique:

microseconds: [0, 999999]
Seconds: [0, 86399]
Days: [-999999999, 999999999]
Class properties

Class Property Name Description
Timedelta.min Timedelta (-999999999)
Timedelta.max Timedelta (days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
Timedelta.resolution Timedelta (Microseconds=1)
Instance methods and properties

Instance method/Property name Description
Td.days days [-999999999, 999999999]
Td.seconds sec [0, 86399]
Td.microseconds μs [0, 999999]
Td.total_seconds () The total number of seconds contained in the time difference, equivalent to: Td/timedelta (Seconds=1)
Method/Property Description
Datetime.datetime.now () returns the current local time (Datetime.datetime object instance)
Datetime.datetime.fromtimestamp (timestamp) returns the time corresponding to the specified timestamp (Datetime.datetime object instance)
Datetime.timedelta () Returns a time interval object that can be added and reduced directly to the Datetime.datetime object
Instance

>> Import datetime
>>
>> Datetime.timedelta (365). Total_seconds () # Total seconds contained in a year
31536000.0
>> dt = Datetime.datetime.now ()
>> DT + Datetime.timedelta (3) # 3 days later
Datetime.datetime (2017, 2, 8, 9, 39, 40, 102821)
>> DT + Datetime.timedelta (-3) # 3 days ago
Datetime.datetime (2017, 2, 2, 9, 39, 40, 102821)
>> DT + Datetime.timedelta (hours=3) # 3 hours later
Datetime.datetime (2017, 2, 5, 12, 39, 40, 102821)
>> DT + Datetime.timedelta (hours=-3) # 3 hours ago
Datetime.datetime (2017, 2, 5, 6, 39, 40, 102821)
>> DT + Datetime.timedelta (hours=3, seconds=30) # 3 hours 30 seconds later
Datetime.datetime (2017, 2, 5, 12, 40, 10, 102821)
Five, Time format code

The Struct_time of the time module, as well as the DateTime, date, and times classes of the DateTime module, provide the Strftime () method, which outputs a timing string in the specified format. The format is composed of a series of format codes (format characters), Python finally calls the Strftme () function of each platform C library, so the support of the platform for the full set of format codes will be different, depending on the platform of the Strftime (3) document. All format codes required by the C standard (version 1989) are listed below, and they work on all standard C-implemented platforms:

Vi. Summary

Is it good to use the time module or the datetime module in Python? As far as I am concerned, the DateTime module can basically meet the needs, and it is indeed more convenient to use. For the time module, I only use the Time.time () method when I take the timestamp of the current time, and of course it can be obtained by Datetime.datetime.now (). Timestamp (). I think it is better to look at personal habits, there is no absolute good or bad points.

Python 3 Date and time processing module (date and datetime)

Related Article

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.