【问题标题】:Adding seconds to datetime [duplicate]在日期时间中添加秒数[重复]
【发布时间】:2017-01-09 15:13:55
【问题描述】:

我正在努力为时间戳添加不同的秒数。

假设我想将 1136 秒添加到 2016-12-02 13:26:49。这是我迄今为止所拥有的:

import datetime

if __name__ == '__main__':
    timestamp = datetime.datetime(year=2016, month=12, day=02, hour=13, minute=26, second=49)
    offset = 1140
    m, s = divmod(offset, 60)
    h, m = divmod(m, 60)

我在 another post 中看到了与我想要的类似的东西,但这不适用于 Python。

我应该使用datetime.datetime.combine()吗?

我有大量数据,我不想手动输入每个总和的日期。

提前感谢您的帮助。

【问题讨论】:

标签: python datetime utc


【解决方案1】:

您可以使用timedelta 将秒数添加到日期时间对象。

>>> import datetime
>>> now = datetime.datetime.now()
>>> now 
datetime.datetime(2017, 1, 9, 16, 16, 12, 257210)
>>> now + datetime.timedelta(seconds=1136)
datetime.datetime(2017, 1, 9, 16, 22, 12, 257210)
>>> 

【讨论】:

  • 也许可以将秒数修改为1136,因为这是问题所在(尽管我承认这是一个细节)。
【解决方案2】:

只需将timedelta 添加到timestamp

timestamp = datetime.datetime(year=2016, month=12, day=02, hour=13, minute=26, second=49)
d = datetime.timedelta(seconds=1136)
new_timestamp = timestamp+d

在控制台中运行:

$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> timestamp = datetime.datetime(year=2016, month=12, day=02, hour=13, minute=26, second=49)
>>> d = datetime.timedelta(seconds=1136)
>>> new_timestamp = timestamp+d
>>> new_timestamp
datetime.datetime(2016, 12, 2, 13, 45, 45)

所以结果是 2016 年 12 月 12 日 13:45:45。

【讨论】:

    【解决方案3】:

    添加timedelta

    >>> import datetime
    >>> timestamp = datetime.datetime(year=2016, month=12, day=2, hour=13, minute=26, second=49)
    >>> timestamp += datetime.timedelta(seconds=1136)
    >>> timestamp
    datetime.datetime(2016, 12, 2, 13, 45, 45)
    

    【讨论】:

      【解决方案4】:

      使用时间增量。

      import datetime
      from datetime import timedelta
      
      timestamp = datetime.datetime(year=2016, month=12, day=02, hour=13, minute=26, second=49)
      
      #offset = 1140
      #m, s = divmod(offset, 60)
      #h, m = divmod(m, 60)
      extra = timedelta(seconds=1136)
      
      print timestamp + extra
      

      【讨论】:

        【解决方案5】:

        我知道,已经有 四个 答案,但请考虑使用 箭头 模块。它使许多日期和时间操作变得更加容易。

        >>> import arrow
        >>> arrow.get('2016-12-02 13:26:49').shift(seconds=+1136)
        <Arrow [2016-12-02T13:45:45+00:00]>
        >>> newTime = arrow.get('2016-12-02 13:26:49').shift(seconds=+1136)
        >>> newTime.strftime('%d-%m-%y')
        '02-12-16'
        

        在导入后的第一条语句中,您可以看到箭头可以将您的时间戳转换为内部时间格式并在一行代码中进行转换。

        在下一个语句中,我保存了该结果并展示了以通常的方式操作内部格式很容易。 (更多可用箭头。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-16
          • 1970-01-01
          • 2018-12-27
          • 2019-01-03
          • 2017-12-21
          • 1970-01-01
          • 2023-01-19
          • 2015-12-23
          相关资源
          最近更新 更多