


A summary of Python time conversion that you can learn in one go (super complete)
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

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.
unix
The 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:

##1.2 Timestamp conversion website
The following introduces severaltimestamps and specific times Websites that convert to each other:
1. Webmaster Tools: https://tool.chinaz.com/tools/unixtime.aspx2. Online Tools: https: //tool.lu/timestamp/3. Json online parsing: https://www.sojson.com/unixtime.html4. Unix timestamp online conversion (rookie tool) : https://c.runoob.com/front-end/8525. 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

2.2calendar
We display the calendar for the upcoming 2020, using the default parameters:
import calendar year = calendar.calendar(2020) print(year)

Change the parameters and display it again:
year = calendar.calendar(2020,w=3,l=1,c=8) print(year)

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:

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

##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
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

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)

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

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

Let’s take a look Calendar for March 2020:

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:

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:

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

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)

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

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

##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.

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


The parameter of ctime
defaults to a timestamp; if not, you can also specify a timestamp3.7mktime
mktime()
also takes a time tuple as a parameter, and it returns a timestamp , is equivalent to the reverse process of localtime
:

##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:

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

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

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 classtimedelta
: time interval, that is, the length of time between two time pointstzinfo
: time zone class
4.1模块内容


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

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)
2、date类中时间和时间戳的转换:

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

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
4、修改日期使用replace
方法

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
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
再看看相关对象和属性相关:
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
4.5timedelta
timedelta
对象表示的是一个时间段,即两个日期date
或者日期时间datetime
之间的差;支持参数:weeks、days、hours、minutes、seconds、milliseconds、microseconds


4.6tzinfo
本地时间指的是我们系统本身设定时区的时间,例如中国处于北京时间,常说的东八区UTC+8:00
。datetime
类有一个时区属性tzinfo
。
tzinfo
是一个关于时区信息的类,是一个抽象的基类,不能直接被实例化来使用。它的默认值是None
,无法区分具体是哪个时区,需要我们强制指定一个之后才能使用。

因为本身系统的时区刚好在中国处于东八区,所以上述代码是能够正常运行的,结果也是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
2、通过astimezone()
将时区指定为我们想转换的时区,比如东八区(北京时间):
# 通过astimezone切换到东八区 beijing = utc_now.astimezone(timezone(timedelta(hours=8))) print(beijing) # 结果 2020-12-26 09:36:33.975427+08:00
用同样的方法切到东九区,东京时间:
# UTC时区切换到东九区:东京时间 tokyo = utc_now.astimezone(timezone(timedelta(hours=9))) print(tokyo) # 结果 2020-12-26 10:36:33.975427+09:00
还可以直接从北京时间切换到东京时间:
# 北京时间(东八区)直接切换到东京时间(东九区) tokyo_new = beijing.astimezone(timezone(timedelta(hours=9))) print(tokyo_new) # 结果 2020-12-26 10:36:33.975427+09:00

5.常用时间转化
下面介绍几个工作中用到的时间转化小技巧:
时间戳转日期
日期转时间戳
格式化时间
指定格式获取当前时间
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'
假设我们指定一个具体的时间戳来进行转换:
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'
如果我们不想指定具体的格式,只想获取时间戳对应的时间,直接通过time.ctime
即可:
import time time.ctime(1608852741) # 结果 'Fri Dec 25 07:32:21 2020'
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

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

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
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
