简体   繁体   English

Python如何处理时间转换?

[英]How does Python handle time conversions?

Recently I have been working on a time series data set and have written a script to automate some plotting. 最近,我一直在研究时间序列数据集,并编写了脚本来自动化一些绘图。 Using the pd.to_datetime function (provided with a specific format), I assumed would automatically convert every time entry to the appropriate format. 我假设使用pd.to_datetime函数(提供了特定格式),每次输入都会自动将其转换为适当的格式。

The raw data follows this format:
%d/%m/%YYYY HH:MM (HH:MM is irrelevant in this case so don't worry about it as we are only interested in the daily average)

However, it seems Python intermittently changes the 'raw timestamps' and changes the format to: %d-%m-%YYYY 但是,Python似乎间歇性地更改了“原始时间戳记”并将格式更改为:%d-%m-%YYYY

Why is this the case and how can I make sure Python doesn't do this? 为什么会这样,如何确保Python不这样做?

I have received the below error and struggle to work out why this is the case. 我收到以下错误,并努力找出为什么会这样。 I have looked at the following SO but I don't have the same issue. 我看了下面的SO,但是没有相同的问题。 time data does not match format 时间数据与格式不匹配

The data itself is provided in the following CSV and is all in the %d/%m/%Y format. 数据本身以以下CSV格式提供,并且全部采用%d /%m /%Y格式。

错误信息

My code for my function is attached in case there are any errors with how I've converted the timestamps. 附上我的函数代码,以防时间戳转换方式出错。

def plotFunction(dataframe):
    for i in wellNames:
        my_list = dataframe["Date"].values
        DatesRev = []

        for j in my_list:
            a=j[0:10]
            DatesRev.append(a)
        #We now need to re-add the dates to our data frame
        df2 = pd.DataFrame(data= DatesRev)
        df2.columns = ["DatesRev"]
        dataframe["DatesRev"] = df2["DatesRev"]
#         print (dataframe)
#         #df2= pd.DataFrame(DatesRev) 
#         #df2.columns = ['DatesRev']    
#         #dataframe['DatesRev'] = df2['DatesRev']
        wellID = dataframe[dataframe['Well']==i]
        wellID['DatesRev'] = pd.to_datetime(wellID['DatesRev'], format='%d/%m/%Y')
        print (i)
#         ax = wellID.set_index('DatesRev').plot()
#         xfmt = mdates.DateFormatter('%d-%m-%Y')
#         ax.xaxis.set_major_formatter(xfmt)
#         plt.xticks(rotation=90)
#         ax.legend(bbox_to_anchor=(1.04,1), loc="upper left")
#         plt.title(i)
#         plt.show()
#         plt.savefig(i + ".jpg", bbox_inches='tight') 

The problem is that python does not recognize / very well. 问题是python无法识别/很好。 I came across this problem myself. 我自己遇到了这个问题。 Dashes are what it recognizes the best. 短划线是公认的最好的东西。 If I may suggest, try to keep the - formatting. 如果我建议,请尝试保留-格式。 It is just Python being Python. 只是Python是Python。 :P :P

In wellID['DatesRev'] , change format='%d/%m/%Y' to format='%d-%m-%Y' and that should possibly fix your problem. wellID['DatesRev'] ,将format='%d/%m/%Y'更改为format='%d-%m-%Y' ,这应该可以解决您的问题。

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

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