首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将值转换为日期格式以及如何将值转换为时间格式

如何将值转换为日期格式以及如何将值转换为时间格式
EN

Stack Overflow用户
提问于 2019-04-10 11:21:36
回答 3查看 624关注 0票数 0

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

代码语言:javascript
运行
AI代码解释
复制
df['Time'] 
540.0 
630.0
915.0
1730.0
2245.0 

df['Date']
14202.0
14202.0
14203.0
14203.0

我需要为这两列创建具有正确数据格式的新列,以便能够在不同的列中分析日期和时间的数据。

对于['Time'],我需要将格式转换为:

代码语言:javascript
运行
AI代码解释
复制
 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.实现的方法。

我尝试了不同类型的代码,但没有任何效果,例如,我尝试过的代码之一是以下代码:

代码语言:javascript
运行
AI代码解释
复制
# 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'],我也有同样的问题--没有日期就没有时间,我也试着插入“:”,但即使将数据类型转换为string,也无法工作。

我希望有人能在这件事上帮助我,如果有任何疑问请告诉我,有时很难解释。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-04-29 03:08:26

用日期解决问题

from datetime import datetime

from datetime import timedelta

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

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

startdate_object #打印startdate_object以检查日期

创建一个列表,以便在dataframe中添加一个具有日期格式的新列

import math datenew = []

dates = df['UTS_Date'] #原始列'UTS_Date‘中的数据

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

if math.isnan(values):

代码语言:javascript
运行
AI代码解释
复制
    `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)) #检查新列表数据的长度,以确保数据上的所有行都在新列表中

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

票数 0
EN

Stack Overflow用户

发布于 2019-04-29 03:08:13

关于时间转换:

代码语言:javascript
运行
AI代码解释
复制
# 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_]
票数 0
EN

Stack Overflow用户

发布于 2019-04-29 03:14:41

用时间解决问题

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

times = df['Time'] #变量时间等于数据的df‘times’列

变量来查找时间的位置,即>= 2400。

i = 0

def Normalize_time (val):

代码语言:javascript
运行
AI代码解释
复制
`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):

代码语言:javascript
运行
AI代码解释
复制
    `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)) #检查新列表的时间长度,以确保数据上的所有行都在新列表中

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55619895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档