Home > Backend Development > Python Tutorial > A summary of Python time conversion that you can learn in one go (super complete)

A summary of Python time conversion that you can learn in one go (super complete)

Release: 2023-08-11 16:12:59
forward
642 people have browsed it

In life and work, each of us interacts with time every day Dealing with:

  • #When do you get up in the morning?

  • #How many minutes does it take for the subway to arrive?

  • #When does the lunch break start at noon?

  • What day is tomorrow?

  • #It’s been 2 months since I last bought clothes?

  • #My boss asked me to add a scheduled task function to the code. What should I do?

Different situations will encounter different time issues: Specific time points, time intervals, days of the week, etc. We are always in touch with time. collision. This article will use Python to explain in detail time-related classes, their methods and properties

A summary of Python time conversion that you can learn in one go (super complete)

1. Timestamp

1.1 Introduction to timestamps

Before we formally explain time-related functions, we must first have a concept: Timestamps. This article specifically refers to the unix timestamp.

Timestamp Timestamp refers to adding identifying text, such as time or date, to a series of data to ensure that the local data update sequence is consistent with the remote one.

unixThe timestamp is the number of seconds elapsed since January 1, 1970 (midnight UTC/GMT), regardless of leap seconds. 1970-01-01 is often the time we get after converting the empty timestamp when the time in MySQL is empty. One hour is expressed as a UNIX timestamp in the format of 3600 seconds; one day is expressed as a UNIX timestamp of 86400 seconds, and leap seconds are not counted. The specific comparison table is as follows:

A summary of Python time conversion that you can learn in one go (super complete)

##1.2 Timestamp conversion website

The following introduces several

timestamps and specific times Websites that convert to each other:

1. Webmaster Tools: https://tool.chinaz.com/tools/unixtime.aspx

2. Online Tools: https: //tool.lu/timestamp/

3. Json online parsing: https://www.sojson.com/unixtime.html

4. Unix timestamp online conversion (rookie tool) : https://c.runoob.com/front-end/852

5. Beijing Time (time and timestamp exchange tool): http://www.beijing-time.org/shijianchuo/

After introducing the basic knowledge of timestamps, let’s focus on three Python libraries related to time and date:

  • calendar

  • time

  • datetime

2.calendar

calendar in Chinese means "calendar", so it is actually suitable for dates, especially in the form of a calendar.

2.1 Module content

A summary of Python time conversion that you can learn in one go (super complete)
The following are examples:

2.2calendar

We display the calendar for the upcoming 2020, using the default parameters:

import calendar
year = calendar.calendar(2020)
print(year)
Copy after login

A summary of Python time conversion that you can learn in one go (super complete)

Change the parameters and display it again:

year = calendar.calendar(2020,w=3,l=1,c=8)
print(year)
Copy after login

A summary of Python time conversion that you can learn in one go (super complete)

We found that the entire calendar has become wider, and the English of the week is also It is displayed with 3 letters. Please explain the meaning of the 3 parameters:

  • c: Monthly interval distance

  • w: Daily width interval

  • l: Number of rows per week

where The length of each line is: 21*w 18 2*c, 3 months per line

Finally, take a look at the upcoming 2021 calendar:

A summary of Python time conversion that you can learn in one go (super complete)

2.3isleap(year)

The function of this function is to determine whether a certain year is a leap year. If so, it returns True, otherwise it returns False.

Ordinary years can be divisible by 4, but not by 100, and are called ordinary leap years.

Years that are in hundreds must be divisible by 400, and are called centuries. Leap year

A summary of Python time conversion that you can learn in one go (super complete)

##2.4leapdays(y1,y2)

Determine how many days there are between two years Leap year , including y1, but not y2, similar to in Python slicing, including the head but not the tail

A summary of Python time conversion that you can learn in one go (super complete)

2.5month(year,month,w=2,l=1)

This function returns year## The month month calendar has only two rows of titles, one for each week. The daily interval width is w characters, and the length of each line is 7*w 6, where l is the number of lines per week

First look at the default effect;

A summary of Python time conversion that you can learn in one go (super complete)
Next we change the two parameters w and l:

1. Change

w, and we find that the representation of the week becomes 3 letters; At the same time, the intervals between each day have become wider (left and right intervals)

A summary of Python time conversion that you can learn in one go (super complete)
2. Changing the parameters

l, we found that the intervals before each week (up and down) ) has become wider

A summary of Python time conversion that you can learn in one go (super complete)
##2.6monthcalendar(year,month)

Returns the calendar of year, month, and month in the form of a list, In a list or in list form. Each sublist is for a week.

If there is no date of this month, 0 is used to represent

. Each sublist starts from week 1, and its characteristics are summarized as follows:

  • Each sublist represents a week

  • From Monday to Sunday, the dates that do not appear in this month are replaced with 0

  • We still take December 2020 as an example:

A summary of Python time conversion that you can learn in one go (super complete)Compared with the calendar above, we found that:
The position where 0 appears does not appear in December

Let’s take a look Calendar for March 2020:

A summary of Python time conversion that you can learn in one go (super complete)

2.7monthrange(year,month)

The result returned by this function is a tuple with two values ​​in the tuple(a,b)

  • The value a represents the day of the week that the month starts; 6 represents Sunday, and the value is 0-6

  • The value b represents the total number of days in the month

I will explain it through an example, still taking December 2020 Take the month as an example:

A summary of Python time conversion that you can learn in one go (super complete)

The 1 in the result means that December starts on the 2nd of the week (0-6, 6 represents Sunday), and the month has a total of 31 days

2.8weekday(y,m,d)

The weekday method is to enter the year, month and day, and we can know the day of the week; The return value is 0-6, 0 represents Monday, 6 represents Sunday

Let’s explain it through an example, taking December 12th as an example:

A summary of Python time conversion that you can learn in one go (super complete)

Double 12 is Saturday , the returned result is 5, and 5 represents Saturday, which exactly matches.

3.time

The time module is involved in the time function The most commonly used module is often used in Python's time-related requirements. The following is a detailed explanation of how to use this module.

3.1 Module content

Let’s first look at the overall use of the module

A summary of Python time conversion that you can learn in one go (super complete)

3.2time

##time.time() is to get the current time, more strictly speaking, to get The timestamp of the current time.

Understand the timestamp again: it starts from 0:00:00 on January 1, 1970, and calculates to the current length of time (not considering leap seconds)

A summary of Python time conversion that you can learn in one go (super complete)

3.3localtime

time.localtime is print the current time, get The result is a time tuple, the specific meaning is:

Note: the result is a time tuple

A summary of Python time conversion that you can learn in one go (super complete)
# The parameter of ##time.localtime

defaults to the timestamp of time.time(). You can enter a timestamp yourself to get the corresponding time

  • Default current timestamp

  • Specify a timestamp

A summary of Python time conversion that you can learn in one go (super complete)

##3.4gmtime

##localtime()

The result is local time, if internationalization is required, use gmtime(), preferably Greenwich Time. Greenwich Mean Time: Standard time at the Royal Greenwich Observatory in the suburbs of London, England, where the Prime Meridian passes.

A summary of Python time conversion that you can learn in one go (super complete)
3.5asctime

When the parameter of time.asctime

is empty, the default is The value of time.localtime is the parameter to get the current date, time and week; in addition, we can also set the parameters ourselves, the parameter is the time tuple

  • Use the default time tuple localtime of the current time

  • Specify a time tuple yourself

A summary of Python time conversion that you can learn in one go (super complete)Get the specific time and date of the current time:

A summary of Python time conversion that you can learn in one go (super complete)##3.6ctime

The parameter of ctime

defaults to a timestamp; if not, you can also specify a timestamp

A summary of Python time conversion that you can learn in one go (super complete)

3.7mktime

mktime() also takes a time tuple as a parameter, and it returns a timestamp , is equivalent to the reverse process of localtime:

A summary of Python time conversion that you can learn in one go (super complete)

##3.8strftime

strftime() converts the time tuple into a string according to the format we specify ; if the time tuple is not specified, the default is the current time localtime(). The commonly used time formats are shown in the following table:

A summary of Python time conversion that you can learn in one go (super complete)
We give an example:

  • The delimiters in the string are You can specify it arbitrarily

  • You can display the year, month, day, hour, minute, second, etc. at the same time

A summary of Python time conversion that you can learn in one go (super complete)

3.9strptime

strptime() converts a string into a time tuple. What we need to pay special attention to is that it has two parameters:

  • The string to be converted

  • #The format corresponding to the time string, the format is the above? table mentioned in

A summary of Python time conversion that you can learn in one go (super complete)

4.datetime

Although the time module is already able It solves many problems, but in actual work and business needs, more tools are needed to make us more convenient and faster to use. datetime is one of the very useful modules. Several commonly used classes in the datetime module are as follows:

  • date: date class, common attributes: year/month/day

  • time: Time class, common attributes: hour/minute/second/microsecond

  • datetime: date time class

  • timedelta: time interval, that is, the length of time between two time points

  • tzinfo: time zone class

4.1模块内容

A summary of Python time conversion that you can learn in one go (super complete)

A summary of Python time conversion that you can learn in one go (super complete)


4.2date

首先我们引入date类,并创建一个日期对象:

A summary of Python time conversion that you can learn in one go (super complete)

1、然后我们可以操作这个日期对象的各种属性:后面加上()

print("当前日期:",today)  # 当前日期
print("当前日期(字符串):",today.ctime())   # 返回日期的字符串
print("时间元组信息:",today.timetuple())   # 当前日期的时间元组信息
print("年:",today.year)   # 返回today对象的年份
print("月:",today.month)  # 返回today对象的月份
print("日:",today.day)   # 返回today对象的日
print("星期:",today.weekday())  # 0代表星期一,类推
print("公历序数:",today.toordinal())  # 返回公历日期的序数
print("年/周数/星期:",today.isocalendar())   # 返回一个元组:一年中的第几周,星期几

# 结果显示
当前日期: 2020-12-25
当前日期(字符串):Fri Dec 25 00:00:00 2020
时间元组信息:time.struct_time(tm_year=2020, tm_mon=12, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=360, tm_isdst=-1)
年: 2020
月: 12
日: 25
星期: 4
公历序数: 737784
年/周数/星期: (2020, 52, 5)
Copy after login

2、date类中时间和时间戳的转换:

A summary of Python time conversion that you can learn in one go (super complete)

具体时间的时间戳转成日期:

A summary of Python time conversion that you can learn in one go (super complete)

3、格式化时间相关,格式参照time模块中的strftime方法

from datetime import datetime, date, time
today = date.today()

print(today)
# 2020-12-26  默认连接符号是-

print(today.strftime("%Y/%m/%d"))  # 指定连接符
# 2020/12/26

print(today.strftime("%Y:%m:%d"))
# 2020:12:26

print(today.strftime("%Y/%m/%d %H:%M:%S"))  # 转化为具体的时间
# 2020/12/26 00:00:00
Copy after login

4、修改日期使用replace方法

A summary of Python time conversion that you can learn in one go (super complete)

4.3time

time类也是要生成time对象,包含hour、minute、second、microsecond,我们还是通过例子来学习:

from datetime import time

t = time(10,20,30,40)
print(t.hour)  # 时分秒
print(t.minute)
print(t.second)
print(t.microsecond)  # 微秒

# 结果
10
20
30
40
Copy after login

4.4datetime

datetime类包含date类和time类的全部信息,下面?是类方法相关的:

from  datetime import datetime

print(datetime.today())
print(datetime.now())
print(datetime.utcnow())# 返回当前UTC日期和时间的datetime对象
print(datetime.fromtimestamp(1697302830))  # 时间戳的datetime对象
print(datetime.fromordinal(699000) )
print(datetime.combine(date(2020,12,25), time(11,22,54)))  # 拼接日期和时间
print(datetime.strptime("2020-12-25","%Y-%m-%d"))

# 结果
2020-12-25 23:24:42.481845
2020-12-25 23:24:42.482056
2020-12-25 15:24:42.482140
2023-10-15 01:00:30
1914-10-19 00:00:00
2020-12-25 11:22:54
2020-12-25 00:00:00
Copy after login

再看看相关对象和属性相关:

from datetime import datetime 

d = datetime(2020,12,25,11,24,23)

print(d.date())
print(d.time())
print(d.timetz())  # 从datetime中拆分出具体时区属性的time
print(d.replace(year=2021,month=1))  # 替换
print(d.timetuple())  # 时间元组
print(d.toordinal())  # 和date.toordinal一样
print(d.weekday())
print(d.isoweekday())
print(d.isocalendar())
print(d.isoformat())
print(d.strftime("%Y-%m-%d :%H:%M:%S"))

# 结果
2020-12-25
11:24:23
11:24:23
2021-01-25 11:24:23
time.struct_time(tm_year=2020, tm_mon=12, tm_mday=25, tm_hour=11, tm_min=24, tm_sec=23, tm_wday=4, tm_yday=360, tm_isdst=-1)
737784
4
5
(2020, 52, 5)
2020-12-25T11:24:23
2020-12-25 :11:24:23
Copy after login

4.5timedelta

timedelta对象表示的是一个时间段,即两个日期date或者日期时间datetime之间的差;支持参数:weeks、days、hours、minutes、seconds、milliseconds、microseconds

A summary of Python time conversion that you can learn in one go (super complete)

A summary of Python time conversion that you can learn in one go (super complete)

4.6tzinfo

本地时间指的是我们系统本身设定时区的时间,例如中国处于北京时间,常说的东八区UTC+8:00datetime类有一个时区属性tzinfo

tzinfo是一个关于时区信息的类,是一个抽象的基类,不能直接被实例化来使用。它的默认值是None,无法区分具体是哪个时区,需要我们强制指定一个之后才能使用。

A summary of Python time conversion that you can learn in one go (super complete)

因为本身系统的时区刚好在中国处于东八区,所以上述代码是能够正常运行的,结果也是OK的。那如果我们想切换到其他时区的时间,该如何操作呢?这个时候我们需要进行时区的切换。

1、我们先通过utcnow()获取到当前的UTC时间

utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)  # 指定utc时区
print(utc_now)

# 结果
2020-12-26 01:36:33.975427+00:00
Copy after login

2、通过astimezone()将时区指定为我们想转换的时区,比如东八区(北京时间):

# 通过astimezone切换到东八区

beijing = utc_now.astimezone(timezone(timedelta(hours=8)))
print(beijing)

# 结果
2020-12-26 09:36:33.975427+08:00
Copy after login

用同样的方法切到东九区,东京时间:

# UTC时区切换到东九区:东京时间

tokyo = utc_now.astimezone(timezone(timedelta(hours=9)))
print(tokyo)

# 结果
2020-12-26 10:36:33.975427+09:00
Copy after login

还可以直接从北京时间切换到东京时间

# 北京时间(东八区)直接切换到东京时间(东九区)

tokyo_new = beijing.astimezone(timezone(timedelta(hours=9)))
print(tokyo_new)

# 结果
2020-12-26 10:36:33.975427+09:00
Copy after login

A summary of Python time conversion that you can learn in one go (super complete)

5.常用时间转化

下面介绍几个工作中用到的时间转化小技巧:

  1. 时间戳转日期

  2. 日期转时间戳

  3. 格式化时间

  4. 指定格式获取当前时间

5.1时间戳转成日期

时间戳转成具体时间,我们需要两个函数:

  • time.localtime:将时间戳转成时间元组形式

  • time.strftime:将时间元组数据转成我们需要的形式

import time
now_timestamp = time.time()  # 获取当前时间的时间戳

# 时间戳先转成时间元组,strftime在转成指定格式
now_tuple = time.localtime(now_timestamp)
time.strftime("%Y/%m/%d %H:%M:%S", now_tuple)

# 结果
'2020/12/26 11:19:01'
Copy after login

假设我们指定一个具体的时间戳来进行转换:

import time
timestamp = 1608852741  # 指定时间戳

a = time.localtime(timestamp)  # 获得时间元组形式数据
print("时间元组数据:",a)
time.strftime("%Y/%m/%d %H:%M:%S", a)  # 格式化

# 结果
时间元组数据:time.struct_time(tm_year=2020, tm_mon=12, tm_mday=25, tm_hour=7, tm_min=32, tm_sec=21, tm_wday=4, tm_yday=360, tm_isdst=0)
'2020/12/25 07:32:21'
Copy after login

如果我们不想指定具体的格式,只想获取时间戳对应的时间,直接通过time.ctime即可:

import time
time.ctime(1608852741)

# 结果
'Fri Dec 25 07:32:21 2020'
Copy after login

5.2日期时间转成时间戳

日期时间转成时间戳格式,我们需要使用两个方法:

  • strptime():将时间转换成时间数组

  • mktime():将时间数组转换成时间戳

通过具体的案例来学习一下:

date = "2020-12-26 11:45:34"

# 1、时间字符串转成时间数组形式
date_array = time.strptime(date, "%Y-%m-%d %H:%M:%S")

# 2、查看时间数组数据
print("时间数组:", date_array)

# 3、mktime时间数组转成时间戳
time.mktime(date_array)

# 结果
时间数组:time.struct_time(tm_year=2020, tm_mon=12, tm_mday=26, tm_hour=11, tm_min=45, tm_sec=34, tm_wday=5, tm_yday=361, tm_isdst=-1)
1608954334.0
Copy after login

A summary of Python time conversion that you can learn in one go (super complete)

5.3格式化时间

工作需求中有时候给定的时间格式未必是我们能够直接使用,所以可能需要进行格式的转换,需要使用两个方法:

  • strptime():将时间转换成时间数组

  • strftime():重新格式化时间

通过案例来进行学习:

import time

old = "2020-12-12 12:28:45"

# 1、转换成时间数组
time_array = time.strptime(old, "%Y-%m-%d %H:%M:%S")

# 2、转换成新的时间格式(20201212-20:28:54)
new = time.strftime("%Y%m%d-%H:%M:%S",time_array)  # 指定显示格式

print("原格式时间:",old)
print("新格式时间:",new)

# 结果
原格式时间: 2020-12-12 12:28:45
新格式时间: 20201212-12:28:45
Copy after login

A summary of Python time conversion that you can learn in one go (super complete)

5.4指定格式获取当前时间

为了能够获取到指定格式的当前时间,我们分为3个步骤:

  • time.time():获取当前时间

  • time.localtime():转成时间元组

  • time.strftime():重新格式化时间

通过一个案例来学习:

# 1、时间戳
old_time = time.time()
# 2、时间元组
time_array = time.localtime(old_time)
# 3、指定格式输出
new_time = time.strftime("%Y/%m/%d %H:%M:%S", time_array)
print(new_time)

# 结果
2020/12/26 11:56:08
Copy after login

6.总结

本文通过各种案例详细介绍了Python中关于时间输出和转化的3个模块:calendar、time、datetime,最后总结了4个工作中常用的时间转化技巧,希望对大家掌握Python中的时间输出和转化有所帮助,不再被时间困扰。

The above is the detailed content of A summary of Python time conversion that you can learn in one go (super complete). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Python当打之年
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