Python time operations are here!

There are three modules for processing time in Python, datetime, time, calendar, and integrate three modules to make it possible to use Python to process time as you wish. This article is written for this purpose. The focus of the article is to tease out the design context of the three modules so that everyone can remember the api inside. When you need to be able to find the appropriate method. However, due to the limited use of the calendar module, due to space limitations, this article does not deal with it.

1 Overview

Datetime module is mainly used to represent the date, that is, we often say the date and time of day, month, calendar module is mainly used to indicate the date of the month, is the information of the day of the week, time module main focus in the hour and minute seconds, rough From a functional point of view, we can think of the three as a complementary relationship, each focusing on one. It is convenient for the user to select the handy module according to different purposes of use.

2. Speaking from the time module

In order to learn the time module, we need to know a few concepts related to time:

(1)epoch

Suppose we want to represent the time as milliseconds, say 1,000,000 milliseconds. Then there is a problem that must be solved. What time is the starting point of 1,000,000 milliseconds, that is, what time is our time base point? Like I said you are 1.8 meters tall, and that height means talking to the ground you stand on. This time reference point is epoch. In the Unix system, this benchmark is at 0:00 on January 1, 1970.

(2) GMT, UTC

Above, we say that epoch represents the starting point of 1970. Which 1970 is the reference time? Generally speaking, it is relative to Greenwich Mean Time, also known as GMT (Greenwich Mean Time), also called UTC (Coordinated Universal Time). What is a time base with two names? Historically, prior GMT and later UTC.

UTC is the time standard we use now. GMT is the old time measurement standard. UTC calculates time based on the atomic clock, and GMT calculates time based on the rotation and revolution of the earth.

Therefore, it can be considered that UTC is the true reference time, and the deviation of GMT from UTC is zero.

In practice, our computer has a hardware module RCT, which records UTC time in real time. The module has a separate battery supply, even if the shutdown does not affect.

With the time base of epoch and the benchmark of UTC, we can accurately represent the time.

(3) DST, tzone

Although we can accurately express a time, in many cases, we still need to adjust the time according to the actual situation in the region. The most common is the time zone, tzone, I believe we are all familiar with.

At this point, when we say 5:5 this time, we need to add 5:5 which time zone to accurately explain a time.

Another DST is to adjust the time.

The full name of DST is Daylight Saving Time, which means that in order to make full use of sunlight and reduce electricity consumption, artificially make an adjustment to the time, which depends on the policies and regulations of different countries and regions. For example, suppose you get up at 7 o'clock in the morning and get up at 6 o'clock in the summer. Then when the summer arrives, you will add 1 hour to the time. This will make you still feel like you get up at 7 o'clock, but actually it is an hour earlier.

So, for us who are curious, we must ask, how does python know the values ​​of tzone and DST? The answer is through environmental variables.

Here we only take Linux as an example to illustrate.

There are TZ environment variables in Linux, and their values ​​are similar to this:

CST+08EDT, M4.1.0, M10.5.0, this string can be interpreted as follows, separated by spaces, divided into three parts

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

The CST in the first part represents the name of the time zone, ie China Standard Time, which is what we call Beijing time, +8 means that Beijing time plus 8 hours is UTC time

The second part of the EDT represents the name of the DST. We say that the DST varies according to the policies and regulations of various countries and regions. The EDT can also be followed by a time adjustment value just after the CST, but since we only have 86 to 92 years in our country. After a certain period of time, DST has been abolished, so no adjustments will be made later.

The third part shows the starting and ending time of the implementation of DST. We do not interpret it in detail.

(4) Representation of time, acquisition, conversion

The basic way to get time in the time module is

t = time.time()

It returns the number of seconds from the epoch (indicated by floating-point numbers) using UTC time.

We naturally want to convert this number of seconds into year, month, day, minute, and second, and this conversion is divided into two types. One is still to use UTC time, which is an adjustment time in our time zone.

The time module provides us with two methods,

Time. gmtime(t)

Time.localtime(t)

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

This representation is more suitable for our understanding than the time in seconds.

If these two functions are called without passing arguments, they will call time.time() internally and convert them with the number of seconds returned.

In contrast, Python also provides a way to convert these two struct_times to seconds.

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

Time.mktime() is used to convert the struct_time (that is, the return object of the localtime) object with the time zone adjustment to the number of seconds since the epoch.

In other words, the mktime method will first find the time zone and DST information in the system, and use this information to adjust the struct_time and convert it into seconds.

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

The strftime and strptime in the time module do this.

To see the names, everyone should know what they mean.

Strftime string format time, used to format time into a string

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

It should be noted that the time here is the struct_time object.

About how to format the time, it is a very simple knowledge, here's the content of the official website.

In addition to these two functions, the time module also provides two simple methods to help convert the time into a string

Asctime is used to convert a struct_time object to a standard 24-character string as follows:

Sun Jun 20 23:21:05 1993

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

The above is the core content of the time module, I tried to use a recipe to help memorize these APIs

Time time seconds

Incoming gm, local time struct_time

To change back to the original number of seconds

You have to pass back calendar.timegm and time. mktime

String f and string p

Formatting time is based on the brothers

You are still too busy

Asctime, ctime to help

Dedicated to help you turn the string

The former receives struct_time

The latter specifically deals with the number of seconds

Division of labor is effortless

Learn the basic functions of the time module

Make time to understand people!

Below, we want to start learning the datetime module.

3.datetime module

(1) Overview

The time module solves the acquisition and representation of the time, and the datetime module further solves the problem of quickly obtaining the hour, minute, and second information in the operation time.

Simply put, the core class of the module is three, the date class represents the date, the time class represents the minute, second, and millisecond. Do not confuse this with the time module. A dogger can help to keep track of this situation:

No time inside time

Hidden in datetime

Isn't the code editorial? Well, I think so too.

The datetime class is a combination of date and time.

It is necessary to explain in advance that the time class and datetime class have an attribute. Its value is a tzinfo object that contains the time zone information of the time or datetime. Generally, this time or datetime object is aware, and it can be accurate. Converted to the number of seconds since the epoch.

If the property is set to None, then the time object or datetime object at this time does not have time zone information. It specifically indicates whether it is local time or utc time. It needs to be determined by the program itself.

The local time we are talking about here refers to the time in our time zone. The utc time refers to the international standard time, which is GMT. Same hereafter.

Remember, there is no time zone information in date.

(2) starting from the creation of datetime

Create a datetime object, my most common method is as follows

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

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

There is a question here. Is this datetime object utc or local?

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

Get a datetime object that represents the current local time, there are two easy ways

Datetime. datetime. now()

Datetime. datetime. today()

Above we get the local datetime object, how to obtain utc datetime object? There are two ways

Datetime. datetime. utcfromtimestamp()

Datetime. datetime. utcnow()

We can also create datetime objects from strings,

The method is datetime.striptime(date_string, format)

Its internal or first call the striptime method in the time module, obtain the struct_time object, and then use the struct_time object in the year, month, day, hour, minute, and second information to construct a datetime object.

Similarly, the datetime class also provides the strftime(), asctime(), and ctime() methods, and I'm sure you don't know what you are doing.

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

It should be noted that when the timestamp is present in the datetime module, it can generally be understood as the number of seconds returned by time.time().

(3) Creation of date and time

The creation of the date object is very similar to the datetime.

Datetime. date. today()

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

Of course, you can also create date objects by passing constructors with year, month, and day.

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

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

This method is created.

(4) Operation and timedelta of the above three objects

In practical use, we have a large demand for comparing and adding and subtracting dates. Thanks to Python's operator overloading capabilities, Python can be easily

Less than (<) comparisons and subtraction (-) operations between date objects, or between datetime objects.

Note that this is limited to objects of the same class and does not include time objects.

Two date objects are subtracted, or two datetime objects are subtracted. The difference is represented by a timedelta object.

Similarly, a date object or datetime object can also add or subtract a timedelta object.

A timedelta object has three attributes: days, seconds, microseconds, and the days attribute can take a negative value, and the other two attributes can only be positive values.

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

Between two timedelta objects can be added, can be reduced, but can not do size comparison, because it does not make sense.

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

Can also be negated, or use the abs function to get the absolute value

4. No summary, no progress

The purpose of this article is not to elaborate on how Python handles the use of time and date APIs, but rather to get an overview of the design structure of the time and datetime modules so that you can understand what capabilities these modules provide and what they need. When you can think of it and use it, as for the detailed api, it should be easy to solve.

The Mining Transformer

The Mining Transformer,Mining Transformer,Electric Power Transformer,Electric Transformer

SANON DOTRANS Co., Ltd. , https://www.sntctransformer.com