【问题标题】:Convert UNIX timestamp to str and str to UNIX timestamp in python [duplicate]在python中将UNIX时间戳转换为str并将str转换为UNIX时间戳[重复]
【发布时间】:2013-12-14 05:44:23
【问题描述】:

例如:

我想将 UNIX 时间戳 1385629728 转换为 str "2013-11-28 17:08:48"
并将 str "2013-11-28 17:08:48" 转换为 UNIX 时间戳 1385629728

【问题讨论】:

  • 请避免在 SO 上直接问谷歌问题。它降低了平均问题的标准。

标签: python


【解决方案1】:

按如下方式进行:

#-*-coding:utf-8-*-

import datetime, time

def ts2string(ts, fmt="%Y-%m-%d %H:%M:%S"):
    dt = datetime.datetime.fromtimestamp(ts)
    return dt.strftime(fmt)

def string2ts(string, fmt="%Y-%m-%d %H:%M:%S"):
    dt = datetime.datetime.strptime(string, fmt)
    t_tuple = dt.timetuple()
    return int(time.mktime(t_tuple))

def test():
    ts = 1385629728

    string = ts2string(ts)
    print string

    ts = string2ts(string)
    print ts

if __name__ == '__main__':
    test()

【讨论】:

    【解决方案2】:

    你应该使用日期时间。

    >>> import datetime
    >>> print(datetime.datetime.fromtimestamp(int("1385629728")).strftime('%Y-%m-%d %H:%M:%S'))
    2013-11-28 14:38:48
    >>> print int(datetime.datetime.strptime('2013-11-28 14:38:48', '%Y-%m-%d %H:%M:%S').strftime("%s"))
    1385629728
    

    【讨论】:

    • 这类回答我最喜欢。谢谢!
    【解决方案3】:
    import time 
    
    # where epoch is your epoch time value 
    time.strftime("%a, %d %b %Y %H:%M:%S +0000", 
                            time.localtime(epoch))
    

    Source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-07
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2017-07-18
      • 2020-10-19
      • 2013-02-14
      • 2013-07-02
      相关资源
      最近更新 更多