简体   繁体   English

如何为 Python 做 PHP 的 strtotime 函数

[英]How to do strtotime function of PHP for Python

First: Sorry my bad english ok?第一:对不起,我的英语不好好吗? Second: I already looked at this post python - strtotime equivalent?第二:我已经看过这篇文章python - strtotime 等价物?

So, i'm trying to use the function strtotime('+{amount} days or minutes') in Python.所以,我试图在 Python 中使用函数strtotime('+{amount} days or minutes') This function is PHP, but in Python how to do?这个函数是PHP的,但是在Python中怎么办?

I'm using Django我正在使用 Django

I'm doing this def :我这样做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

First, I'd recommend looking into simply using dateparser as they have implemented similar functionality: https://dateparser.readthedocs.io/en/latest/首先,我建议考虑简单地使用dateparser因为它们已经实现了类似的功能: https : dateparser


But, for the sake of completeness, let's also make your function work for your provided use-case.但是,为了完整起见,让我们也让您的函数为您提供的用例工作。 Namely, the "{num} minute|hour|day|week|year" example.即, "{num} minute|hour|day|week|year"示例。 I assume you'd want to chain these as well, so this works for things like 1 year 3 days 5 minutes .我假设你也想链接这些,所以这适用于1 year 3 days 5 minutes类的事情。

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

This uses a dict to avoid all the if / elif branches.这使用 dict 来避免所有if / elif分支。 It uses a regex with grouping to iterate through all {num} {timeunit} patterns of the string, and adds the corresponding length of time to an accumulator which is initialized as the current time, giving us the offset.它使用带分组的正则表达式遍历字符串的所有{num} {timeunit}模式,并将相应的时间长度添加到初始化为当前时间的累加器中,为我们提供偏移量。

Here are examples (formatted to see what it does):以下是示例(格式化以查看其作用):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM