【发布时间】:2019-04-10 19:21:36
【问题描述】:
我有两列,一列的值代表时间,另一列的值代表日期(两个值都是浮点型),我在每一列中都有以下数据:
df['Time']
540.0
630.0
915.0
1730.0
2245.0
df['Date']
14202.0
14202.0
14203.0
14203.0
我需要为这两列创建具有正确数据格式的新列,以便能够分析不同列中包含日期和时间的数据。
对于['Time'],我需要将格式转换为:
540.0 = 5h40 OR TO 5.40 am
2245.0 = 22h45 OR TO 10.45 pm
对于['Date'],我需要将格式转换为:
我们可以说代表“天”的每个数字:
其中 0(“天”)= 01-01-1980
所以如果我将 01-01-1980 添加到 14202.0 = 18-11-1938
如果我添加:01-01-1980 + 14203.0 = 19-11-1938,
这种方法可以用 excel 做,但我需要用 Python 做。
我尝试了不同类型的代码,但没有任何效果,例如,我尝试的代码之一是以下代码:
# creating a variable with the data in column ['Date'] adding the days into the date:
Time1 = pd.to_datetime(df["Date"])
# When I print it is possible to see that 14203 in row n.55384 is added at the end of the date created but including time, and is not what I want:
print(Time1.loc[[55384]])
55384 1970-01-01 00:00:00.000014203
Name: Date, dtype: datetime64[ns]
# printing the same row (55384) to check the value 14203.0, that was added above:
print(df["Date"].loc[[55384]])
55384 14203.0
Name: Date, dtype: float64
对于['Time'],我也有同样的问题,没有日期就没有时间,我也尝试插入':',但即使将数据类型转换为字符串也无法正常工作。
我希望有人可以帮助我解决这个问题,有任何疑问请告诉我,有时并不容易解释。
【问题讨论】:
-
重新格式化问题,这个看着也很痛苦。只需对所有代码使用一个块并描述您的问题。
-
嗨@ilamaaa,请看一下这样更好还是分成两个不同的问题更好?
-
看起来像我不是专家的excels日期和时间格式,最初获取数据时使用pandas read_excel是否可行。
-
我只是举了一个例子来说明如何用 Excel 解决问题,以演示我需要 Python 的输出
-
首先我将 Excel 文件导入 Microsoft SQL 服务器,因为它是一个大文件,可以直接从 Excel 中工作。我正在使用 'df = pd.read_sql_query' 从 Sql 服务器读取数据。唯一的问题是找到一个可以从日期和时间做我需要的代码。
标签: python date data-conversion