Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common operations about time in the Python library

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge about "what are the common operations about time in Python library". In the operation process of actual cases, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

time package

import time

timestamp

How many seconds have elapsed since the birth of the Standard Time Zone on January 1, 1970 at 00:00:00?

code

timestamp = time.time() # type:float print(timestamp, type(timestamp))

execution result

sleep

Sometimes we may need to mimic IO requests and pretend to put the program to sleep, so we need to use the sleep function of time.

code

#sleep for 1 second time.sleep(1)

local time zone

Local time zone requires localtime method of time.

code

t = time.localtime() # type:time.struct_time print(t, type(t))

execution result

localtime can also receive a timestamp parameter.

code

#convert timestamp to struct_time object t = time.localtime(1606395685.1878598) # type:time.struct_time print(t, type(t))

execution result

Simple time format

code

t = time.ctime() # type:str print(t, type(t))

execution result

Although this can show the time, but this format is not very good.

Time.ctime() can also receive a timestamp.

code

t = time.ctime(1606395685.1878598) # type:str print(t, type(t))

execution result

time formatting

Date Format-> String (strftime)

code

t = time.localtime() # type:time.struct_time t_str = time.strftime("%Y-%m-%d", t) # type:str print(t_str, type(t_str))

execution result

String Date-> Date (strptime)

code

t_str = "2020-11-02" t_time = time.strptime(t_str, "%Y-%m-%d") # type:time.struct_time print(t_time, type(t_time))

execution result

格式化补充

主要有如下格式

具体详见:

https://www.runoob.com/python/python-date-time.html

datetime包

注:datetime和time是两个不同的类型,不能混用。

from datetime import datetime

datetime.today()

代码

t = datetime.today() # type:datetime print(t, type(t)) print(t.year) # 年份 print(t.month) # 月份

执行结果

datetime.now()

和datetime.today()基本一样,返回的是本地时间。

代码

t = datetime.now() # type:datetime print(t,type(t))

执行结果

datetime.utcnow()

utcnow返回的是标准(UTC)时间,上述俩返回的都是本地时间,我们是东八区!

代码

t = datetime.now() print("东八区时间:", t) t = datetime.utcnow() # type:datetime print("UTC时间:", t)

执行结果

时间戳转datetime

有时候,我们拿到的,就是时间戳,那就只能转了。

代码

# 时间戳 timestamp = time.time() print(f"timestamp:{timestamp},type:{type(timestamp)}") # 时间戳转datetime t = datetime.fromtimestamp(timestamp) print(f"t:{t},type:{type(t)}")

执行结果

datetime -> 字符串日期(strftime)

代码

from datetime import datetime t = datetime.now() str_datetime = t.strftime("%Y-%m-%d %H:%M:%S") print(f"字符串日期:{str_datetime},type:{type(str_datetime)}")

执行结果

字符串日期 -> datetime(strptime)

代码

from datetime import datetime str_datetime = "2020-11-29 22:05:20" t = datetime.strptime(str_datetime, "%Y-%m-%d %H:%M:%S") print(f"t:{t},type:{type(t)}")

执行结果

时间加减

这才是本次的重头戏,好像只有datetime这个包,才有时间加减的。

时间加减的具体用途很多,必须多久过期什么的,多久之后提醒,都需要提前计算时间,还是很重要的。

代码

from datetime import datetime import datetime as idatetime t = datetime.now() print(f"当前时间:{t}") three_day = t + idatetime.timedelta(days=3) print(f"三天后时间:{three_day}")

执行结果

可以发现,这个时间确实是+成功了。

但是自带的时间加减,有个题,只能加天,不能加月,甚至年。

如果想要时间+月等,还要自己写逻辑。

datetime时间自由加减

有个包正好解决了这个问题。

安装

pip install python-dateutil

代码

from datetime import datetime from dateutil.relativedelta import relativedelta t = datetime.now() print(f"当前时间:{t}") three_time = t + relativedelta(months=3) print(f"三个月后时间:{three_time}") one_year = t+relativedelta(years=1) print(f"一年后时间:{one_year}") up_year = t+relativedelta(years=-1) print(f"去年这个时间:{up_year}")

执行结果

用法很简单,如果想加月/年份,就写正数,如果想减,就写负数,这个方法基本上将python在操作时间上的缺点给弥补了。

"Python库中关于时间的常见操作有哪些"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report