Time Processing summary in python and python processing summary

Source: Internet
Author: User
Tags timedelta

Time Processing summary in python and python processing summary
Beijing and Shanghai tour site | nvidia dli deep learning trainingJanuary 26, 2018/January 12 NVIDIA deep learning institute takes you into the hot DL Field
Read the full text>



The body contains a total of 4858 words and three images. The expected reading time is 13 minutes.


In python, there are three time processing modules: datetime, time, and calendar. Only by integrating these modules can you use python to process time as you like. This article focuses on organizing the design context of the three modules, so that you can easily remember the APIs in it. You can find the corresponding method as needed. However, since the calendar module is not used much, it is not covered in this article due to its limited space.

Overview



The datetime module is mainly used to represent the date, that is, the year, month, day, hour, minute, and second. The calendar module is mainly used to represent the year, month, day, week, and other information. The time module mainly focuses on the hour, minute, and second, in terms of functions, we can consider the three as a complementary relationship and focus on each other. It is convenient for users to select a handy module based on different purposes.

Starting from the time module



To learn the time module, we need to first understand several time-related concepts:


1. epoch


Suppose we want to express the time as the number of milliseconds, for example, 1000000 milliseconds, there is a problem that must be solved. What is the start time of this 1000000 milliseconds, that is, what is our time benchmark? For example, if I say you are 1.8 tall, this height is relative to the ground where you stand. This time point is epoch. in Unix systems, this point is the time point at zero o'clock, January 1, January 1, 1970.


2. GMT and UTC


As we said above, epoch indicates the starting point of 1970. Which benchmark time is this 1970 month relative? Generally, compared with Greenwich Mean Time, GMT (Greenwich Mean Time) is also called UTC (Coordinated Universal Time). Why does one Time benchmark have two names? In history, the first GMT and the last UTC.


UTC is our current time standard, while GMT is the old time measurement standard. UTC calculates the time based on the atomic clock, while GMT calculates the time based on the rotation and revolution of the Earth.


Therefore, UTC is the real reference time, and the deviation between GMT and UTC is 0.


In practice, our computer has a hardware module, the IDC, which records the UTC time in real time. This module has a separate battery power supply, and will not affect the shutdown.


With epoch and UTC, we can accurately represent a time.


3. DST and tzone


Although we can accurately represent a time, in many cases, we still need to adjust the time according to the actual situation of the region, the most common is the time zone, tzone, I believe everyone is familiar with it.


At this time, when we say 05:05, we still need to add the time zone 05:05 to precisely describe a time.


Another adjustment to the time is DST.


DST stands for Daylight Saving Time. It means that to make full use of Daylight and reduce electricity usage, it is determined by policies and regulations of different countries and regions. For example, if you get up at in winter, but at in summer, you can manually add an hour when the summer arrives, so that you can still get up, but it is actually one hour ahead of schedule.


So, curious, we must ask, How does python know the values of tzone and DST? The answer is through environment variables.


Here we only use linux as an example.


In linux, there are TZ environment variables whose values are similar to the following:


CST + 08EDT, M4.1.0, and M10.5.0. The strings can be interpreted as follows, separated by spaces, and divided into three parts:


CST + 08 EDT, M4.1.0, M10.5.0


In the first part, CST indicates the Time zone name, that is, China Standard Time, that is, Beijing Time. + 8 indicates Beijing Time minus 8 hours, that is, UTC Time.


In the second part, EDT indicates the name of DST. We say that DST varies with policies and regulations in different countries and regions. EDT can also add a time adjustment value as after CST, however, since we only implemented DST for a period of time from 86 to 92 years in China, it has now been abolished, so there is no need to adjust the time later.


The third part indicates the start time and end time of DST.


4. Time Representation, acquisition, and conversion


The basic method for obtaining the time in the time module is


T = time. time ()


It returns the number of seconds from epoch to the present (expressed by a floating point number) and the UTC time.


We naturally want to convert the number of seconds to the format of year, month, day, hour, minute, and second. There are two types of conversion: one is UTC time, and the other is the time after adjustment using our time zone.


The time module provides us with two methods,


Time. gmtime (t)

Time. localtime (t)


Both return an instance of struct_time class, which has the following attributes:


Picture from simplified book App


This representation is more suitable for us to understand than the time expressed in seconds.


If the two functions are not called, they call time. time () internally and use the returned number of seconds for conversion.


On the contrary, python also provides the method to convert struct_time to seconds.


The calendar. timegm () method is used to convert the struct_time (returned object of gmtime) of UTC to the number of seconds from epoch.


Time. mktime () is used to convert the struct_time (returned object of localtime) object adjusted with the time zone to the number of seconds from epoch.


That is to say, the mktime method will first find the time zone and DST information in the system, and use this information to adjust struct_time and then convert it to the number of seconds.


Another common requirement is to convert the string between time and time.


The strftime and strptime in the time module are used for this purpose.


You should know the meaning of the names,

Strftime is the string format time, which is used to format the time into a string.

Strptime is the string parse time, which is used to parse the string into time.


Note that the time here is a struct_time object.


It is very easy to learn how to format the time. Here we will use the content of the official website documentation.


Picture from simplified book App


In addition to these two functions, the time module provides two simple methods to convert time into strings.


Asctime is used to convert a struct_time object to a standard 24-character string, as shown below:


Sun Jun 20 23:21:05 1993


The ctime method has the same effect as asctime, except that it receives the number of seconds. Internally, it first converts the number of seconds to struct_time through localtime, and then becomes the same as asctime.


The above is the core content of the time module. I try to use a phrase to help remember these Apis.


Time: time. The number of seconds.


Input gm, struct_time for local time

To change back to original seconds

You have to return the calendar. timegm and time. mktime

String f and string p

The formatting time depends on the two

You have to worry about it.

Asctime, ctime to help

Specially Used to convert strings

The former receives struct_time

The latter is dedicated to processing seconds

Labor division and cooperation

Learn Basic time module skills

Make time clear!


Next, we will start to learn the datetime module.


Datatime Module


1. Overview


The time module obtains and represents the time, while the datetime module further improves the ability to quickly obtain and operate the information of the year, month, day, hour, minute, and second in the time.


Simply put, there are three core classes in this module. The date class indicates the year, month, and day, and the time class indicates the hour, minute, and second milliseconds. Do not confuse the time module here. You can easily remember this situation:


There is no time in time

Hidden in datetime

Isn't it easy? Well, I think so too.

Datetime class is a combination of date and time.


One thing to note in advance is that both the time class and the datetime class have an attribute. Its value is a tzinfo object, which contains the time zone information of the time or datetime, generally, this time or datetime object is aware, which can be accurately converted to the number of seconds since epoch.


If this attribute is set to None, the time object or datetime object does not have the time zone information, which indicates the local time or utc time, we need to make our own decisions in the program.


The local time here refers to the time in our time zone, and utc time refers to the international standard time, that is, Greenwich Mean time. The following is the same.


Remember that there is no time zone information in date.


2. Start from datatime Creation


To create a datetime object, use the following methods:


Dt = datetime. datetime. fromtimestamp (time. time ())


Above, time. time () gets the number of seconds since epoch. The fromtimestamp method converts this number of seconds into a datetime object.


Here is a question: Is the datetime object utc or local?


The answer is local, which is the default behavior of this method. If you input a parameter indicating the time zone in the fromtimestamp method, that is, the tzinfo object, it will be converted according to the passed time zone information.


To obtain the datetime object that represents the current local time, there are two simple methods:


Datetime. datetime. now ()

Datetime. datetime. today ()


All of the above are datetime objects of local. How can we get datetime objects of utc? There are two methods:


Datetime. datetime. utcfromtimestamp ()

Datetime. datetime. utcnow ()


You can also create a datetime object from the string using the datetime. striptime (date_string, format) method)


Internally, the striptime method in the time module is called to obtain the struct_time object, and then the datetime object is constructed using the year, month, day, hour, minute, and second information in the struct_time object.


Similarly, the datetime class also provides the strftime (), asctime (), ctime () methods. I believe you know what it is.


The datetime class also provides a combine method to combine a date object and a time object into a datetime object.


Note that when a timestamp is displayed in the datetime module, it can be interpreted as the number of seconds returned by time. time.


3. Create data and time


Date object creation is very similar to datetime, datetime. date. today ()

Datetime. date. fromtimestamp () can all create a date object.


Of course, you can also use the constructor to input the year, month, and day to create the date object.

In contrast, the creation of the time object is very limited and can only be passed through:


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


This method is created.


4. operations on the above three objects and timedelta class


In actual use, we need to compare and add or subtract dates. Thanks to the python operator Overload Capability, python can conveniently compare and subtract between date objects or datetime objects by less than (<.


Note: Only between similar objects and between time objects are allowed.


Two date objects are used for subtraction, or between two datetime objects. The difference value is represented by a timedelta object.


Likewise, a date object or datetime object can be added or subtracted from a timedelta object.


A timedelta object contains three attributes: days, seconds, microseconds, and days. The other two attributes can only be positive values.


You can use the total_seconds () method to obtain the number of seconds of a timedelta object.


Two timedelta objects can be added or subtracted, but cannot be compared in size, because this makes no sense.


A timedelta object can also be multiplied by an integer or be divided by a // operation.


You can also obtain the inverse value or use the abs function to obtain the absolute value.


No summary, no progress



The purpose of this article is not to explain in detail how to use the python time and date Processing api, but to use an overview to let everyone grasp the design structure of the time and datetime modules, in this way, you can clearly understand the capabilities provided by these modules and use them when necessary. As for detailed api queries, it should be easy to solve.


Link: https://www.jianshu.com/p/a035a564b248


For more concise and convenient classification articles and the latest courses and product information, please go to the newly presented "LeadAI college Official Website ":

Www.leadai.org


Please follow the artificial intelligence LeadAI public account to view more professional articles

Everyone is watching

Application of LSTM model in Q & A System

TensorFlow-Based Neural Networks solve the problem of user loss Overview

Sort out the most common questions for algorithm Engineers (1)

Sort out the most common questions for algorithm Engineers (2)

TensorFlow starts from 1 to 2 | Chapter 3 deep learning revolution: convolutional Neural Network

Decorator | Python Advanced Programming

Let's review the basics of Python today.


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.