Python 创建未来五分钟后的unix时间戳

发布于 2024-08-31 19:33:30 字数 530 浏览 2 评论 0原文

我必须在未来 5 分钟内创建一个“过期”值,但我必须以 UNIX 时间戳格式提供它。到目前为止我已经有了这个,但它看起来像是一个黑客。

def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    epoch = datetime.datetime(1970, 1, 1)
    seconds_in_a_day = 60 * 60 * 24
    five_minutes = datetime.timedelta(seconds=5*60)
    five_minutes_from_now = datetime.datetime.now() + five_minutes
    since_epoch = five_minutes_from_now - epoch
    return since_epoch.days * seconds_in_a_day + since_epoch.seconds

是否有模块或函数可以为我进行时间戳转换?

I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack.

def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    epoch = datetime.datetime(1970, 1, 1)
    seconds_in_a_day = 60 * 60 * 24
    five_minutes = datetime.timedelta(seconds=5*60)
    five_minutes_from_now = datetime.datetime.now() + five_minutes
    since_epoch = five_minutes_from_now - epoch
    return since_epoch.days * seconds_in_a_day + since_epoch.seconds

Is there a module or function that does the timestamp conversion for me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

此刻的回忆 2024-09-07 19:33:30

另一种方法是使用 calendar.timegm

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return calendar.timegm(future.timetuple())

它也比 %s 标志更容易移植到 strftime(这在 Windows 上不起作用)。

Another way is to use calendar.timegm:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return calendar.timegm(future.timetuple())

It's also more portable than %s flag to strftime (which doesn't work on Windows).

看透却不说透 2024-09-07 19:33:30

现在在 Python >= 3.3 中,您只需调用 timestamp() 方法 获取浮点数形式的时间戳。

import datetime
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp() # works if Python >= 3.3

unix_timestamp_plus_5_min = unix_timestamp + (5 * 60)  # 5 min * 60 seconds

Now in Python >= 3.3 you can just call the timestamp() method to get the timestamp as a float.

import datetime
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp() # works if Python >= 3.3

unix_timestamp_plus_5_min = unix_timestamp + (5 * 60)  # 5 min * 60 seconds
时间海 2024-09-07 19:33:30

刚刚发现这个,而且更短。

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

Just found this, and its even shorter.

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)
離殇 2024-09-07 19:33:30

这就是您所需要的:

import time
import datetime
n = datetime.datetime.now()
unix_time = time.mktime(n.timetuple())

This is what you need:

import time
import datetime
n = datetime.datetime.now()
unix_time = time.mktime(n.timetuple())
黒涩兲箜 2024-09-07 19:33:30

您可以使用 datetime.strftime 获取 Epoch 形式的时间,使用 %s 格式字符串:

def expires():
    future = datetime.datetime.now() + datetime.timedelta(seconds=5*60)
    return int(future.strftime("%s"))

注意:
这只适用于linux,并且此方法不适用于时区。

You can use datetime.strftime to get the time in Epoch form, using the %s format string:

def expires():
    future = datetime.datetime.now() + datetime.timedelta(seconds=5*60)
    return int(future.strftime("%s"))

Note:
This only works under linux, and this method doesn't work with timezones.

风透绣罗衣 2024-09-07 19:33:30

这是一个不太损坏的基于 datetime 的解决方案,用于从 datetime 对象转换为 posix 时间戳:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return (future - datetime.datetime(1970, 1, 1)).total_seconds()

请参阅 Converting datetime Python 中的 .date 到 UTC 时间戳

Here's a less broken datetime-based solution to convert from datetime object to posix timestamp:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return (future - datetime.datetime(1970, 1, 1)).total_seconds()

See more details at Converting datetime.date to UTC timestamp in Python.

蓝色星空 2024-09-07 19:33:30
def in_unix(input):
  start = datetime.datetime(year=1970,month=1,day=1)
  diff = input - start
  return diff.total_seconds()
def in_unix(input):
  start = datetime.datetime(year=1970,month=1,day=1)
  diff = input - start
  return diff.total_seconds()
栀子花开つ 2024-09-07 19:33:30

关键是在开始转换之前确保您使用的所有日期都位于 utc 时区。请参阅 http://pytz.sourceforge.net/ 了解如何正确执行此操作。通过标准化为 utc,您可以消除夏令时转换的歧义。然后你可以安全地使用 timedelta 来计算距 unix 纪元的距离,然后转换为秒或毫秒。

请注意,生成的 unix 时间戳本身位于 UTC 时区。如果您希望查看本地时区的时间戳,则需要进行另一次转换。

另请注意,这仅适用于 1970 年之后的日期。

   import datetime
   import pytz

   UNIX_EPOCH = datetime.datetime(1970, 1, 1, 0, 0, tzinfo = pytz.utc)
   def EPOCH(utc_datetime):
      delta = utc_datetime - UNIX_EPOCH
      seconds = delta.total_seconds()
      ms = seconds * 1000
      return ms

The key is to ensure all the dates you are using are in the utc timezone before you start converting. See http://pytz.sourceforge.net/ to learn how to do that properly. By normalizing to utc, you eliminate the ambiguity of daylight savings transitions. Then you can safely use timedelta to calculate distance from the unix epoch, and then convert to seconds or milliseconds.

Note that the resulting unix timestamp is itself in the UTC timezone. If you wish to see the timestamp in a localized timezone, you will need to make another conversion.

Also note that this will only work for dates after 1970.

   import datetime
   import pytz

   UNIX_EPOCH = datetime.datetime(1970, 1, 1, 0, 0, tzinfo = pytz.utc)
   def EPOCH(utc_datetime):
      delta = utc_datetime - UNIX_EPOCH
      seconds = delta.total_seconds()
      ms = seconds * 1000
      return ms
仙女山的月亮 2024-09-07 19:33:30

以下内容基于上述答案(加上毫秒修正),并在使用时区时模拟 3.3 之前的 Python 3 的 datetime.timestamp()

def datetime_timestamp(datetime):
    '''
    Equivalent to datetime.timestamp() for pre-3.3
    '''
    try:
        return datetime.timestamp()
    except AttributeError:
        utc_datetime = datetime.astimezone(utc)
        return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6

要严格回答所提出的问题,您需要:

datetime_timestamp(my_datetime) + 5 * 60

datetime_timestampsimple 的一部分-日期。但如果您使用该包,您可能会输入:

SimpleDate(my_datetime).timestamp + 5 * 60

它可以处理 my_datetime 的更多格式/类型。

The following is based on the answers above (plus a correction for the milliseconds) and emulates datetime.timestamp() for Python 3 before 3.3 when timezones are used.

def datetime_timestamp(datetime):
    '''
    Equivalent to datetime.timestamp() for pre-3.3
    '''
    try:
        return datetime.timestamp()
    except AttributeError:
        utc_datetime = datetime.astimezone(utc)
        return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6

To strictly answer the question as asked, you'd want:

datetime_timestamp(my_datetime) + 5 * 60

datetime_timestamp is part of simple-date. But if you were using that package you'd probably type:

SimpleDate(my_datetime).timestamp + 5 * 60

which handles many more formats / types for my_datetime.

红ご颜醉 2024-09-07 19:33:30
def expiration_time():
    import datetime,calendar
    timestamp = calendar.timegm(datetime.datetime.now().timetuple())
    returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
    return returnValue
def expiration_time():
    import datetime,calendar
    timestamp = calendar.timegm(datetime.datetime.now().timetuple())
    returnValue = datetime.timedelta(minutes=5).total_seconds() + timestamp
    return returnValue
爱,才寂寞 2024-09-07 19:33:30

请注意,使用 timedelta.total_seconds() 的解决方案适用于 python-2.7+。
对于较低版本的 Python,请使用 calendar.timegm(future.utctimetuple())

Note that solutions with timedelta.total_seconds() work on python-2.7+.
Use calendar.timegm(future.utctimetuple()) for lower versions of Python.

垂暮老矣 2024-09-07 19:33:30

这个使用内置时间戳函数的方法怎么样?该片段适用于不同的时间(不仅仅是当前时间)。

import datetime

a = "2017-01-01 14:30:00"
b = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
c = int(b.timestamp()/60.0)
alarm_time = c + 5

运行时环境
操作系统:Ubuntu 16.04
Python 3.6

How about this method using built-in timestamp function? The snippet is working for different time (not just current time).

import datetime

a = "2017-01-01 14:30:00"
b = datetime.datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
c = int(b.timestamp()/60.0)
alarm_time = c + 5

Runtime environment
  OS: Ubuntu 16.04
  Python 3.6

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文