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

标签 python python-3.x

首先:抱歉我的英语不好好吗? 第二:我已经看过这篇文章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/

相关文章:

python - 创建和初始化 python 列表

python - 逐个构建 DataFrame 的最快方法是什么?

Python virtualenv 问题

python - 当满足特定条件时无法显示另一个 tkinter 框架

python - Django 中的替代管理员

python - tcp python 套接字永远保持连接

python - 比较 Pandas Dataframes 的 boolean 值——返回字符串

python - Pytest 模块未找到错误

python-3.x - 计算2D图像中分支的厚度

python - Pyperclip 的奇怪行为