【问题标题】:How can I Convert Normal timestamp to Epoch Timestamp in python如何在 python 中将普通时间戳转换为纪元时间戳
【发布时间】:2021-05-10 18:42:18
【问题描述】:

问题 1: 将人类可读的日期转换为一天开始时的纪元时间戳/时间? 例子。 如果 INPUT 日期是 21-01-2020,则在一天开始时打印纪元时间,即 12:00 AM 状况: 日期限制:01-01-1970 至 输入说明: 输入日期将采用以下任一格式。

  1. dd/mm/yyyy
  2. mm/dd/yyyy
  3. dd-mm-yyyy
  4. mm-dd-yyyy
  5. dd.mm.yyyy
  6. mm.dd.yyyy
  7. ddmmyyyy
  8. mmddyyyy

输出说明: 对于上述所有类型的输入日期,输出应为 Epoch 时间戳/时间。

问题 1 – 日期到纪元时间戳

例外情况: 必须处理给定格式以外的任何输入日期,并显示消息“无法转换 提供的日期”必须打印出来。

更多例子:

示例 1 输入:2020 年 1 月 19 日 输出:1579392000

示例 2 输入:31122012 输出:1356912000

示例 3 输入:251220202 输出:无法转换提供的日期

示例 4 输入:17:04:2020 输出:无法转换提供的日期

【问题讨论】:

标签: python python-3.x timestamp unix-timestamp epoch


【解决方案1】:
from datetime import datetime
import re

my_input = input("Enter date: ")
my_input = re.sub("/", "-", my_input)
my_input = re.sub(".", "-", my_input)

try:
    out = datetime.strptime(my_input, "%d-%m-%Y").timestamp()
except Exception:
    try:
        out = datetime.strptime(my_input, "%d%m%Y").timestamp()
    except Exception:
        out = "Unable to convert the provided date"

print(out)

    

【讨论】:

  • 由于没有为输入提供时区信息,此代码的结果将取决于您运行它的机器的时区设置。
  • 取决于输入时区。想要更改时区?
猜你喜欢
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-13
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 2018-08-03
  • 2017-07-02
相关资源
最近更新 更多