【问题标题】:How to change value into date format and How to change value into time format如何将值更改为日期格式以及如何将值更改为时间格式
【发布时间】: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


【解决方案1】:

关于时间转换:

# change to integer
tt= [int(i) for i in df['Time']]
# convert to time
time_ = pd.to_datetime(tt,format='%H%M').time
# convert from 24 hour, to 12 hour time format
[t.strftime("%I:%M %p") for t in time_]

【讨论】:

  • 我只是把日期和时间的答案。解决起来很复杂,但现在它可以工作了。问题是不接受时间或数据格式,因为不是 Python 通常接受的正确格式,这是我的问题,但现在已解决,感谢您的帮助。
【解决方案2】:

解决日期问题

from datetime import datetime

from datetime import timedelta

startdate_string = "1980/01/01"#以字符串格式定义开始日期

startdate_object = datetime.strptime(startdate_string, "%Y/%m/%d").date() # 使用 strptime 函数将字符串格式更改为日期对象

startdate_object # 打印 startdate_object 以检查日期

创建一个列表以在数据框中添加一个具有日期格式的新列

import math datenew = []

dates = df['UTS_Date']#来自原始列'UTS_Date'的数据

for values in dates: # 使用 if 语句接受空值并将它们附加到新列表中

if math.isnan(values):

    `datenew.append('NaN')`

    `continue `

`currentdate1 = startdate_object + timedelta(days= float(values))` # add the reference data (startdate_object) to a delta (which is the value in each row of the column)
`datenew.append(str(currentdate1)) ` # converte data into string format and add in the end of the list, removing any word from the list (such: datetime.date)

print (len(datenew))#检查新列表datenew的长度,确保数据上的所有行都在新列表中

df.insert(3, 'Date', datenew) #在数据框中为日期格式创建一个新列

【讨论】:

    【解决方案3】:

    用时间解决问题

    timenew = [] # 创建一个新列表

    times = df['Time']#变量times等于dataframe的df['Time']列

    用于查找 >= 2400 的时间位置的变量

    i = 0

    def Normalize_time (val):

    `offset = 0`
    `if val >= 2400:`
        `offset = 1 ` 
    # converting val into integer, to remove decimal places
    hours = int(val / 100)
    # remove hours and remain just with minutes
    minutes = int(val) - hours * 100 
    # to convert every rows above 24h
    hours = (hours%23) - offset 
    # zfill recognizes that it must have two characters (in this case) for hours and minutes 
    # and if there aren't enough characters,
    # it will add by padding zeros on the left until reaching the number of characters in the argument
    return str(hours).zfill(2) + ':' + str(minutes).zfill(2) 
    

    使用'function Normalize_time()'创建一个for语句来添加新列表中的所有值

    for values in times: # 使用 if 语句接受空值并将它们附加到新列表中 if math.isnan(values):

        `timenew.append('NaN')  `
       ` continue `
    # using values into the function 'Normalize_time()'
    timestr = Normalize_time(values)
    # appending each value in the new list
    timenew.append(timestr)
    

    print(len(timenew))#检查新列表timenew的长度,确保数据上的所有行都在新列表中

    df.insert(4, 'ODTime', timenew) #在数据框中新建一列

    【讨论】:

      猜你喜欢
      • 2020-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 2020-01-30
      • 2019-10-04
      相关资源
      最近更新 更多