gpt4 book ai didi

python - 如何为Python实现PHP的strtotime函数

转载 作者:行者123 更新时间:2023-12-01 06:44:56 24 4
gpt4 key购买 nike

首先:抱歉我的英语不好好吗?第二:我已经看过这篇文章python - strtotime equivalent?

所以,我尝试在 Python 中使用函数 strtotime('+{amount} days or 分钟') 。这个函数是PHP的,但是在Python中怎么做呢?

我正在使用 Django

我正在这样做def:

import time, re

def strtotime(string):
try:
now = int(time.time())
amount = int(re.sub('[^0-9]', '', string))

if 'minute' in string:
return now + (amount * 60)
elif 'hour' in string:
return now + (amount * 3600)
elif 'day' in string:
return now + (amount * 86400)
elif 'week' in string:
return now + (amount * 604800)
elif 'year' in string:
return now + (amount * (365 * 86400) + 86400)
else:
return now + amount
except:
return False

最佳答案

首先,我建议简单地使用dateparser,因为他们已经实现了类似的功能:https://dateparser.readthedocs.io/en/latest/

<小时/>

但是,为了完整起见,我们还要让您的函数适用于您提供的用例。即 “{num} 分钟|小时|日|周|年” 示例。我假设您也想链接这些,因此这适用于 1 年 3 天 5 分钟 之类的事情。

import time, re


def strtotime(string):
unit_to_second = dict(
minute=60, hour=3600, day=86400, week=604800, year=(365 * 86400) + 86400
)
accumulator = time.time()

for match in re.finditer(r"([0-9]) (minute|hour|day|week|year)", string):
num, unit = match.groups()
accumulator += float(num) * unit_to_second[unit]

return accumulator

这使用字典来避免所有 if/elif 分支。它使用带有分组的正则表达式来迭代字符串的所有 {num} {timeunit} 模式,并将相应的时间长度添加到初始化为当前时间的累加器中,从而为我们提供偏移量.

以下是示例(经过格式化以了解其作用):

import datetime

print(datetime.datetime.fromtimestamp(time.time()))
# ==> 2019-12-10 09:41:16.328347

example = strtotime("1 day")
print(datetime.datetime.fromtimestamp(example))
# ==> 2019-12-11 09:41:16.328403

example = strtotime("2 days 5 hours")
print(datetime.datetime.fromtimestamp(example))
# ==> 2019-12-12 14:41:16.328686

example = strtotime("1 week 3 days 2 minutes")
print(datetime.datetime.fromtimestamp(example))
# ==> 2019-12-20 09:43:16.328705

关于python - 如何为Python实现PHP的strtotime函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59272095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com