【问题标题】:How can I delete minutes, seconds and microseconds from a timestamp value using Python?如何使用 Python 从时间戳值中删除分钟、秒和微秒?
【发布时间】:2019-05-23 16:17:14
【问题描述】:

例如,我有 1508265552,即 10/17/2017 @ 6:39pm。我想得到 1508263200,这是同一天但下午 6:00。例如,我有 1508265552,即 10/17/2017 @ 6:39pm。我想得到 1508263200,这是同一天但下午 6:00。

【问题讨论】:

  • 您尝试使用什么代码来执行此操作?你听说过datetime 模块吗?
  • 应该直接使用datetime 格式选择。

标签: python timestamp


【解决方案1】:

使用datetime 模块会更简洁一些。

time 模块是这样的:

import time

# convert to string with minutes and seconds removed.
x = time.strftime('%Y-%m-%d %H:00:00', time.localtime(1508265552))
# convert back to epoch seconds
print(time.mktime(time.strptime(x, '%Y-%m-%d %H:%M:%S')))

结果:

1508263200.0

使用datetime 模块:

import datetime

# convert to datetime
x = datetime.datetime.fromtimestamp(1508265552)
# convert back to epoch seconds with minutes and seconds removed.
print(x.replace(minute=0, second=0).timestamp())

结果:

1508263200.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    相关资源
    最近更新 更多