如何将值更改为日期格式和如何将值更改为时间格式

How to change value into date format and How to change value into time format

我有两列,一列的值代表时间,另一列的值代表日期(两个值都是浮动类型),我在每一列中都有以下数据:

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'],我需要将格式转换为: 我们可以说代表 "days" 的每个数字: 其中 0 ("days") = 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']我有同样的问题我不能没有日期的时间,我也尝试插入':',但即使将数据类型转换为字符串也不起作用。

我希望有人能帮我解决这个问题,有任何疑问请告诉我,有时候不好解释。

关于时间转换:

# 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_]

解决日期问题

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) #在数据框中为日期格式创建一个新列

用时间解决问题

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

times = df['Time'] # 变量时间等于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)) # 检查new list的长度timenew,确保数据上的所有行都在new list中

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