【问题标题】:JSON Imported Unix Timestamps cannot be formattedJSON 导入的 Unix 时间戳无法格式化
【发布时间】:2017-11-27 16:07:37
【问题描述】:

我有一个 JSON 文件,其中包含字符串形式的 unix 时间戳。我正在尝试将这些时间戳转换为人类可读的时间,然后在 matplotlib.pyplot 中显示。

在转换时间戳时出现错误:

ValueError:未转换的数据仍然存在:.1806107

如何将我的日期转换为人类可读的形式YY-MM-DD HH-MM-SS

contents = json.loads(open("foo.json").read()) 
dates = [ ticker['date'] for ticker in contents ]
data = [ ticker['last'] for ticker in contents ]

# Example of array contents
#dates = [1497918349.3060017, 1497918352.9935713, 1497918358.8218484, 1497918364.0406654, 1497918368.9628277]
#data = [1,2,3,4,5]

# Error occurs here
dates=[dt.datetime.strptime(str(date),'%Y%m%d%H%M') for date in dates]

# Also tried the following but I get the error:
# TypeError: an integer is required (got type datetime.datetime)
dates=[dt.datetime.fromtimestamp(date) for date in dates]

plt.plot(dates, data, 'r-')

plt.show()

【问题讨论】:

    标签: python json datetime matplotlib


    【解决方案1】:
    from datetime import datetime
    
    dates = [1497918349.3060017, 1497918352.9935713, 1497918358.8218484, 1497918364.0406654, 1497918368.9628277]
    
    dates = [datetime.utcfromtimestamp(d).strftime('%F %T') for d in dates]
    
    dates
    ['2017-06-20 00:25:49',
     '2017-06-20 00:25:52',
     '2017-06-20 00:25:58',
     '2017-06-20 00:26:04',
     '2017-06-20 00:26:08']
    

    【讨论】:

    • 如果您能用一两句话解释为什么此代码有效但 OP 的代码无效,那就太好了。这将使这个答案对其他人也有用。
    【解决方案2】:

    如果你改变你的

    dates=[dt.datetime.strptime(str(date),'%Y%m%d%H%M') for date in dates]
    

    dates=[dt.datetime.fromtimestamp(date).strftime('%Y%m%d%H%M') for date in dates]
    

    一切都会好的。

    例如:

    from __future__ import print_function
    
    import datetime as dt
    
    dates = [1497918349.3060017, 1497918352.9935713, 1497918358.8218484, 1497918364.0406654, 1497918368.9628277]
    
    # Error used to occur here
    #dates=[dt.datetime.strptime(str(date),'%Y%m%d%H%M') for date in dates]
    dates=[dt.datetime.fromtimestamp(date).strftime('%Y%m%d%H%M') for date in dates]
    
    print(dates)
    

    给予:

    ['201706200325', '201706200325', '201706200325', '201706200326', '201706200326']
    

    请参阅此SO answer 进行详细说明。

    【讨论】:

      猜你喜欢
      • 2016-10-11
      • 1970-01-01
      • 2016-07-17
      • 2020-05-27
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多