首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Delorean,时间处理的终极选择!

处理时间这件事儿,在Python里可不是个简单活。datetime、time这些模块用着都不太顺手,老觉得少点啥。直到我发现了Delorean这个宝贝,那叫一个相见恨晚啊!

要用Delorean,先装它:

pip install Delorean

装好就能开始玩了,超简单的!

看看这操作多痛快:

from delorean import Delorean

from datetime import datetime

# 创建一个时间点

d = Delorean()

print(d) # 当前时间

# 换个时区,分分钟的事

d = d.shift('Asia/Shanghai')

print(d) # 上海时间

# 回到未来!前进3天

future = d.next_day(3)

print(future)

温馨提示:用shift换时区时,时区名要写对,写错了会报错。常用的有’Asia/Shanghai’、’America/New_York’这些。

算时间差、加减时间,用Delorean简直不要太爽:

from delorean import Delorean

# 创建两个时间点

d1 = Delorean()

d2 = Delorean().next_day(5)

# 看看差多少天

diff = d2 - d1

print(f“相差:{diff.days}天”)

# 加上2小时

new_time = d1.add_time(hours=2)

print(new_time)

遇到各种奇怪格式的时间字符串,Delorean也不怂:

from delorean import parse

# 各种格式随便解析

time_str = “2024-01-01 12:30:45”

d = parse(time_str)

print(d)

# 还能自动处理时区

time_with_tz = “2024-01-01 12:30:45 -0500”

d = parse(time_with_tz)

print(d)

想要在两个时间点之间玩转?太简单了:

from delorean import stops

from delorean import Delorean

start = Delorean()

  • 发表于:
  • 原文链接https://page.om.qq.com/page/Oe1PcfJslRO_Q3p3j9Ol6NqQ0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券