在Python中,表示时间的格式一共有3种:时间戳、结构化时间、格式化时间,2个模块:time、datetime。
今天我们来一起看一下。
一、3种时间格式,4种生成方式
1、时间戳 – 记录时间
时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
import time
time.time() # 时间戳
输出:1659682465.1875775
通过这种方式获得的时间一般用于数据库存储,大大节省了存储空间。
[En]
The time obtained in this way is generally used for database storage, which saves storage space very much.
2、结构化的时间 – 使用时间
所谓结构化时间,你可以理解时间的分类,分为:年、月、日、分、秒,你可以直接拿出你想用的类别。
[En]
The so-called structured time, you can understand the classification of time, divided into: year, month, day, minute and second, you can directly take out which category you want to use.
如果我们想取出一个时间段,使用这个方法很简单,例如:取出当前时间的分钟数。
[En]
If we want to take out a time segment, it is very simple to use this method, for example: take out the number of minutes at the current time.
import time
time.localtime().tm_min # 结构化时间
输出:30
3、格式化的时间 – 展示时间
此方法用于向用户显示时间。
[En]
This method is used to show the user the time.
import time
time.strftime('%Y-%m-%d %H-%M-%S %A')# 格式化时间
输出:'2022-08-04 19-08-35 Friday'
import datetime
datetime.datetime.now()#格式化时间
输出:datetime.datetime(2022, 8, 4, 19, 9, 0, 328515)
二、2个模块:time,为什么有datetime模块?
在前面生成时间的代码中,我们使用了2个模块:time和datetime,好像它们之间的功能也是重复的。
既然有了time模块,为什么还要有datetime?那是为了简化time的使用。
datatime模块重新封装了time模块,提供更多接口,提供的类有:date,time,datetime,timedelta,tzinfo。
应用场景
在之前的文章中我们讲过:万字总结!Python 实现定时任务的八种方案
在计划任务中,我想设置一个在一周后提醒我的功能。
[En]
In scheduled tasks, I want to set up a function that reminds me a week later.
如果用time模块进行实现
import time
time.time() + 7*24*60*60 # 7天*24小时*60分钟*60秒
需要自己计算出7天后的时间戳,而如果使用datetime模块,这件事就很简单了:直接 days + 7
,如下图代码所示。
import datetime
datetime.datetime.now() + datetime.timedelta(days=7)#格式化时间
三、互相之间的转换
可以在时间戳、结构化数据和字符串数据之间进行转换。这一点的注意事项如上图所示,我在此不再重复。
[En]
Conversion can be made between timestamps, structured data and string data. The precautions for this point are shown in the picture above, and I will not repeat them here.
如对本篇文章有疑问,可以在评论区,进行更加详细的沟通
Original: https://blog.51cto.com/u_15493782/5548613
Author: Python自动化办公社区
Title: Python是如何表示时间的?2个模块、3种方式,1文搞定~
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/504449/
转载文章受原作者版权保护。转载请注明原作者出处!