【问题标题】:Python convert epoch time to day of the weekPython将纪元时间转换为星期几
【发布时间】:2014-10-07 09:19:33
【问题描述】:

如何在 Python 中做到这一点?我只想返回星期几。

>>> convert_epoch_time_to_day_of_the_week(epoch_time_in_miliseconds)
>>> 'Tuesday'

【问题讨论】:

    标签: python date python-2.7 datetime time


    【解决方案1】:
    ep =  1412673904406
    
    from datetime import datetime
    
    print datetime.fromtimestamp(ep/1000).strftime("%A")
    Tuesday
    
    
    def ep_to_day(ep):
        return datetime.fromtimestamp(ep/1000).strftime("%A")
    

    【讨论】:

    • 纪元为什么要除以1000?
    【解决方案2】:
    import time
    
    epoch = 1496482466
    day = time.strftime('%A', time.localtime(epoch))
    print day
    
    >>> Saturday
    

    【讨论】:

    • 第一篇文章不错!我建议添加解释以改进答案。
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    【解决方案3】:
    from datetime import date
    
    def convert_epoch_time_to_day_of_the_week(epoch_time_in_miliseconds):
        d = date.fromtimestamp(epoch_time_in_miliseconds / 1000)
        return d.strftime('%A')
    

    测试,周二返回。

    【讨论】:

    • 我不认为有很多可能的变化;此外,如果在您写作时发布了答案,则曾经在 SO 上有一个 Ajax 通知,但这次我没有看到……那东西还在工作吗?
    • 不确定,但您需要从毫秒转换才能使其工作
    【解决方案4】:

    如果你有毫秒,你可以使用time模块:

    import time
    time.strftime("%A", time.gmtime(epoch/1000))
    

    返回:

    'Tuesday'
    

    请注意,我们使用%A,如strftime 中所述:

    time.strftime(格式[, t])

    %A 区域设置的完整工作日名称。


    作为一个函数,让我们将毫秒转换为秒:

    import time
    
    def convert_epoch_time_to_day_of_the_week(epoch_milliseconds):
        epoch = epoch_milliseconds / 1000
        return time.strftime("%A", time.gmtime(epoch))
    

    测试...

    今天是:

    $ date +"%s000"
    1412674656000
    

    让我们尝试另一个日期:

    $ date -d"7 Jan 1993" +"%s000"
    726361200000
    

    我们使用这些值运行函数:

    >>> convert_epoch_time_to_day_of_the_week(1412674656000)
    'Tuesday'
    >>> convert_epoch_time_to_day_of_the_week(726361200000)
    'Wednesday'
    

    【讨论】:

    • time.gmtime() 返回 UTC 时间。 time.strftime() 适用于当地时间。你可能想在这里time.localtime(ts)
    猜你喜欢
    • 1970-01-01
    • 2018-04-24
    • 2011-12-06
    • 2012-09-06
    • 2020-12-14
    • 2021-07-27
    • 2014-05-03
    • 2012-01-30
    • 2012-07-29
    相关资源
    最近更新 更多