繁体   English   中英

Python:针对X轴上的时间绘制数据

[英]Python: Plot data against time in X axis

我得到了这样的数据,我想绘制温度与时间的关系

time=`['16:00:00', '16:00:00.013733', '16:00:00.020599', '16:00:00.034332', 
'16:00:00.041199', '16:00:00.048065', '16:00:00.061798', '16:00:00.068665', 
'16:00:00.075531', '16:00:00.089264', '16:00:00.102997', '16:00:00.109863', 
'16:00:00.123596', '16:00:00.130463', '16:00:00.137329', '16:00:00.151062', 
'16:00:00.157928', '16:00:00.171661', '16:00:00.178528', '16:00:00.192261']`

temperature=`[ 691.70001221,  691.54998779,  691.90002441,  691.79998779,
               691.29998779,  691.65002441,  691.59997559,  691.79998779,
               691.95001221,  692.34997559,  691.59997559,  691.34997559,
               690.90002441,  691.40002441,  691.95001221,  690.84997559,
               691.54998779,  691.70001221,  691.95001221,  691.59997559]`

我试图做到这一点

import datetime as DT
datetimes = [DT.datetime.strptime(t, "%H:%M:%S") for t in time]

我停在这里,因为它出现了错误

ValueError: unconverted data remains: .013733

我认为在时间安排中提到秒的小数

谢谢

您的时间以两种不同的格式进行格式化(即一种不带秒的小数,另一种带秒),因此您需要try两种格式:

datetimes = []
for t in time:
    try:
        datetimes.append(DT.datetime.strptime(t, "%H:%M:%S"))
    except ValueError:
        datetimes.append(DT.datetime.strptime(t, "%H:%M:%S.%f"))

另外,如果您确定其余的所有时间都不是几分之一秒,则可以单独处理第一个:

datetimes = ([DT.datetime.strptime(time[0], "%H:%M:%S")] + 
             [DT.datetime.strptime(t, "%H:%M:%S.%f") for t in time[1:]])

您有格式字符串的异构集合。 一些(第一个)的格式为"%H:%M:%S" ,另一些(其余的)的格式为"%H:%M:%S.%f" 因此,编写一个辅助函数:

def datetime_helper(formats, s):
    for f in formats:
        try:
            return datetime.strptime(s, f)
        except ValueError:
            pass

那么您可以执行以下操作:

my_formats = "%H:%M:%S.%f","%H:%M:%S"

[datetime_helper(my_formats,x) for x in time]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM