日期提取,不带“T00:00:00”,格式为%d/%m/%Y

2024-09-30 20:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在处理一个巨大的文本文件。在那里我想阅读和剪熊猫

以下是原始文件的示例:

Date;Time;GHI;DNI;DIF;flagR;SE;SA;TEMP;AP;RH;WS;WD;PWAT
01.01.1994;00:07;0;0;0;0;-41.92;-19.43;14.3;1004.4;93.4;0.3;189;17.7
01.01.1994;00:22;0;0;0;0;-40.65;-23.70;14.3;1004.4;93.6;0.1;186;17.8
01.01.1994;00:37;0;0;0;0;-39.14;-27.75;14.3;1004.3;93.7;0.0;10;18.0

为此,我有一个日期格式%d.%m.%Y,并将其更改为%d/%m/%Y。然后,我在VSCode数据查看器上看到需要排序,因为我的结果是%Y-%m-%d+time。这个time部分总是T00:00:00,我不需要它,因为我已经有时间了。为什么此文本出现在VSCode Data Viewer中?是否总是生成此时间?它被Python忽略了吗?为什么我写的日期格式不起作用

import pandas as pd
import numpy as np
import datetime

# It will read the file: It will separate by semi-colonne,
# and it will ignore the first 56 rows.
file = pd.read_csv('file.txt', 
                    sep = ';', 
                    skiprows = 56)

# It will read the "Date" column to replace the "."
# to "/". This will help the code to read properly the
# date column. Then it will give the format to the 
# whole column [day/month/year]. 

file["Date"] = file["Date"].str.replace('.','/').apply(lambda x: datetime.datetime.strptime(x, "%d/%m/%Y").date())

我使用了上面的代码片段,但它不适用于%d/%m/%Y.date()格式

这是我打印文件时的文件内容:

             Date   Time  GHI  DNI  DIF  flagR     SE     SA  TEMP      AP    RH   WS   WD  PWAT
    0  1994-01-01  00:07    0    0    0      0 -41.92 -19.43  14.3  1004.4  93.4  0.3  189  17.7
    1  1994-01-01  00:22    0    0    0      0 -40.65 -23.70  14.3  1004.4  93.6  0.1  186  17.8
    2  1994-01-01  00:37    0    0    0      0 -39.14 -27.75  14.3  1004.3  93.7  0.0   10  18.0

这是使用VSCode Data Viewer查看文件时的文件内容:

                      Date   Time  GHI  DNI  DIF  flagR     SE     SA  TEMP      AP    RH   WS   WD  PWAT
    0  1994-01-01T00:00:00  00:07    0    0    0      0 -41.92 -19.43  14.3  1004.4  93.4  0.3  189  17.7
    1  1994-01-01T00:00:00  00:22    0    0    0      0 -40.65 -23.70  14.3  1004.4  93.6  0.1  186  17.8
    2  1994-01-01T00:00:00  00:37    0    0    0      0 -39.14 -27.75  14.3  1004.3  93.7  0.0   10  18.0

多谢各位


Tags: 文件thetoreaddatetimesawill
1条回答
网友
1楼 · 发布于 2024-09-30 20:32:27

这就是VScode Data Viewer查看日期的方式,但这并不意味着实际上是这种方式

因此,您可以将Date列的格式替换为以下内容:

file["Date"] =  pd.to_datetime(file['Date'], format='%d.%M.%Y').dt.strftime('%d/%m/%Y')

# write dataframe to CSV file
file.to_csv("out.csv", index=False)

这是CSV文件的内容:

^{tb1}$

相关问题 更多 >