Home > System Tutorial > LINUX > A complete summary of Python time handling

A complete summary of Python time handling

PHPz
Release: 2024-01-26 08:06:16
forward
462 people have browsed it

A complete summary of Python time handling

1 Overview

The datetime module is mainly used to represent dates, which is what we often call year, month, day, hour, minute and second. The calendar module is mainly used to represent year, month, day, day of the week and other information. The time module mainly focuses on hours and minutes. Seconds, from a rough functional point of view, we can think that the three are in a complementary relationship, each focusing on one. It is convenient for users to choose suitable modules according to different purposes.

2. Let’s start with the time module

In order to learn the time module, we need to know several time-related concepts first:

(1)epoch

Suppose we want to express time as a number of milliseconds, such as 1,000,000 milliseconds. Then there is a problem that must be solved. What is the starting point of this 1,000,000 milliseconds, that is, what is our time base point? For example, if I say you are 1.8 meters tall, this height refers to the ground where you stand. This time reference point is epoch. In the Unix system, this reference point is the time point at 0:00 on January 1, 1970.

(2)GMT, UTC

We said above that epoch represents the starting point of 1970, so which base time is this 1970 relative to? Generally speaking, it is relative to Greenwich Time, also called GMT (Greenwich Mean Time) time, and also called UTC (Coordinated Universal Time). Why does a time base have two names? Historically, GMT came first, then UTC.

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

So, UTC can be considered as the real reference time, and the deviation of GMT from UTC is 0.

In reality, our computer has a hardware module RCT, which records UTC time in real time. This module is powered by a separate battery and will not be affected even if it is turned off.

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

(3)DST, tzone

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

At this time, when we say the time of 5:05, we need to add 5:05 in which time zone to accurately describe a time.

Another time adjustment is DST.

DST stands for Daylight Saving Time, which means that in order to make full use of sunlight and reduce electricity consumption, time is artificially adjusted, which depends on the policies and regulations of different countries and regions. For example, if you wake up at 7 o'clock in the winter but get up at 6 o'clock in the summer, then when summer comes, the time is artificially added by 1 hour. This will make you still think you wake up at 7 o'clock, but in fact it is an hour earlier.

So, for those of us who are 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 to illustrate.

There is a TZ environment variable in Linux, its value is similar to this:

CST 08EDT, M4.1.0, M10.5.0, this string can be interpreted as follows, separate them with spaces and divide them 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, which is China Standard Time, which is what we call Beijing time. 8 represents Beijing time plus 8 hours which is UTC time

The second part EDT represents the name of DST. We say that DST is different due to different policies and regulations in various countries and regions. EDT can also be followed by a time adjustment value like CST, but since our country only used it in 1986 DST was implemented for a period of time in 1992, but it has been abolished now, so there is no need to add adjustment time later.

The third part represents the start and end time of implementing DST, so we will not explain it in detail.

(4) Representation, acquisition and conversion of time

The basic method of obtaining time in the time module is

t = time.time()
Copy after login

It returns the number of seconds from epoch to now (expressed as a floating point number), using UTC time.

We naturally want to convert this number of seconds into the form of year, month, day, hour, minute and second, and this conversion is divided into two types, one is still using UTC time, and the other is using the adjusted time in our time zone.

The time module provides us with two methods,

time. gmtime(t)
time.localtime(t)
Copy after login

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

A complete summary of Python time handling

Compared with time expressed in seconds, this expression is more suitable for us to understand.

If these two functions are called without passing parameters, they will call time.time() internally and use the returned seconds for conversion.

On the contrary, python also provides methods to convert these two struct_times into seconds.

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

time.mktime() is used to convert the struct_time (that is, the return object of localtime) object adjusted with the time zone into the number of seconds starting from the 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 into seconds.

Another common need is to convert between a time and a string representing the time.

Strftime and strptime in the time module are used for this.

You should know their meanings by looking at their names,

strftime is string format time, used to format time into a string

strptime is string parse time, used to parse strings into time.

It should be noted that the times here are all struct_time objects.

Regarding how to format time, it is very simple knowledge. Here I will borrow the content from the official website document.

A complete summary of Python time handling

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

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

Sun Jun 20 23:21:05 1993

The ctime method has the same function as asctime, except that it receives seconds. Internally, it will first convert the seconds into struct_time through localtime, and then it will be the same as asctime.

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

time点time得秒数

传入gm, local time得struct_time

要想变回原秒数

你得传回calendar.timegm和time. mktime

string f和string p

格式化时间靠哥俩

你要还是嫌费事

asctime ,ctime来助力

专门帮你转字符串

前者接收struct_time

后者专门处理秒数

分工合作不费力

学好time模块基本功

做个时间的明白人!
Copy after login

Next, we are going to start learning the datetime module.

3.datetime module (1)Overview

The time module solves the problem of obtaining and representing time, and the datetime module further solves the problem of quickly obtaining and manipulating the year, month, day, hour, minute and second information in time.

To put it simply, there are three core classes in this module. The date class represents the year, month and day, and the time class represents the hours, minutes, seconds and milliseconds. Don’t confuse it with the time module here. A jingle can help remember this situation:

There is no time in time

Hidden in datetime

Is the editing bad? Well, I think so too.

The datetime class is a combination of date and time.

One thing that needs to be explained 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. It is generally said that this time or datetime object is aware. It can be accurately converted into seconds since the epoch.

If this property is set to None, then the time object or datetime object does not have time zone information. Specifically, whether it represents local time or utc time, we need to decide in the program ourselves.

The local time we are talking about here refers to the time in our time zone, and utc time refers to the international standard time, which is Greenwich Time. Same below.

Please remember that there is no time zone information in date.

(2)从创建datetime开始

创建datetime对象,我最常用的办法如下

dt=datetime.datetime.fromtimestamp(time.time())

以上,time.time()获得自epoch开始的秒数,fromtimestamp方法会将这个秒数转变成一个datetime对象。

这里有一个问题,这个datetime对象究竟是utc的还是local的?

答案是local的,这是该方法的默认行为。如果你在fromtimestamp方法中传入一个表示时区的参数,即tzinfo对象,就会按传入的时区信息进行转换。

获得表示当前local时间的datetime对象,还有两个简便方法

datetime. datetime. now()
datetime. datetime. today()
Copy after login

以上我们得到的都是local的datetime对象,如何获得utc的datetime对象呢?有两个办法

datetime. datetime. utcfromtimestamp()
datetime. datetime. utcnow()
Copy after login

我们还可以从字符串中创建datetime对象,

其内部还是先调用的time模块中的striptime方法,获取struct_time对象,再利用struct_time对象中的年月日时分秒信息构建datetime对象。

同样的,datetime类也提供了strftime(),asctime(),ctime()方法,相信不说你也知道是做什么的了。

datetime类还提供了一个combine方法,用来将一个date对象和一个time对象组合成一个datetime对象。

需要注意的是,datetime模块中出现timestamp时,一般可将其理解成time.time()返回的秒数

(3)date和time的创建

date对象的创建和datetime非常相似,

datetime. date. today()

datetime.date.fromtimestamp()都可以创建一个date对象。

当然,你也可以通过构造方法传入年月日来创建date对象。

相比之下,time对象的创建就很有限,只能通过

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

这个方法创建。

(4)以上三个对象的操作和timedelta类

在实际使用中,我们有一大块需求就是对日期进行比较和加减运算。得益于python的操作符重载能力,python中可以方便地对

date对象之间,或者datetime对象之间进行小于(

注意,这里仅限于同类对象之间,而且,不包括time对象之间。

两个date对象作减,或者两个datetime对象之间作减,差值用一个timedelta对象表示。

同理,一个date 对象或者datetime对象也可以加或者减一个timedelta对象。

一个timedelta对象含有三个属性:days,seconds, microseconds,days属性可以取负值,另外两个属性都只能是正值。

你可以用total_seconds()方法获得一个timedelta对象的秒数表示。

两个timedelta对象之间可加,可减,但不能做大小比较,因为这样没什么意义。

一个timedelta对象还可以与整数相乘,或通过//操作与一个整数相除。

还可以取反,或者用abs函数获得绝对值

4.无总结,不进步

本文的目的不在于详细说明python处理时间日期的api如何使用,而是想通过一个概览的形式,让大家抓住time和datetime模块的设计结构,从而能够清楚这些模块提供了哪些能力,在需要的时候能够想起来去用,至于查详细的api,应该是可以轻松解决的。

The above is the detailed content of A complete summary of Python time handling. For more information, please follow other related articles on the PHP Chinese website!

source:linuxprobe.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template