【问题标题】:How to format a timestamp in python to a readable format?如何将python中的时间戳格式化为可读格式?
【发布时间】:2019-08-02 14:00:53
【问题描述】:

我有一个 slack 机器人,它可以获取日程信息并打印用户日程的开始和结束时间。我正在尝试格式化时间戳,使其更具可读性。有没有办法格式化这个响应?

这是一个输出示例:

co = get_co(command.split(' ')[1])
start = get_schedule(co['group'])['schedule']['schedule_layers'][0]['start']
end = get_schedule(co['group'])['schedule']['schedule_layers'][0]['end']
response = 'Start: {} \n End: {}'.format(start,end)

当前时间格式是2019-06-28T15:12:49-04:00,但我希望它是像Fri Jun 28 15:12:49 2019 这样更易读的东西

【问题讨论】:

  • 不确定您为什么将 Slack 标记为此答案。有什么相关性吗?
  • 我认为“箭头”有很多选择
  • @ErikKalkoken 我的代码是用于一个 slack 应用程序。 CodeIt 解决了我的问题。我想这个标签是不必要的,如果有问题我会删除它。

标签: python python-3.x time


【解决方案1】:

您可以使用dateparser 轻松解析日期时间字符串。

import dateparser

date = dateparser.parse('2019-06-28T15:12:49-04:00') # parses the date time string

print(date.strftime('%a %b %d %H:%m:%M %Y'))
# Fri Jun 28 15:06:12 2019

查看实际情况here

【讨论】:

    【解决方案2】:

    要转换任何格式的时间戳,您可以使用 datetime 模块,如下所述:

    https://stackabuse.com/converting-strings-to-datetime-in-python/

    【讨论】:

    • 嗨,欢迎来到 SO。感谢您的贡献,但请注意,仅链接的答案通常没有那么有用,因为链接可能会随着时间的推移而失效。相反,请始终在答案中提供相关详细信息。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2015-02-05
    • 2012-06-24
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    相关资源
    最近更新 更多