如何格式化列中的datetime值而不使用pandas中的to\datetime函数?

2024-05-19 13:24:30 发布

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

我有一个如下所示的数据帧

df1_new = pd.DataFrame({'person_id': [1, 1, 3, 3, 5, 5],'obs_date': ['7/23/2377  12:00:00 AM', 'NA-NA-NA NA:NA:NA', 'NA-NA-NA NA:NA:NA', '7/27/2277  12:00:00 AM', '7/13/2077  12:00:00 AM', 'NA-NA-NA NA:NA:NA']})

enter image description here

我不想使用pd.to_datetime方法,因为它强加了年份限制(上限)。OOB error here

下面是我试过的,但效率不高

yr = df1_new['obs_date'][0][5:9]
m = df1_new['obs_date'][0][2:4]
d = df1_new['obs_date'][0][0]
t = df1_new['obs_date'][0][11:19]
output = yr + "-" + m + "-" + d + " " + t

有没有其他有效而优雅的方法可以在不使用pd.datetime函数的情况下实现低于预期的输出

enter image description here

更新的屏幕截图

enter image description here

尝试/除了屏幕截图

enter image description here


Tags: 数据方法iddataframenewdatetimedate屏幕
3条回答

将字符串转换为日期时间时应用try catch

import datetime
import pandas as pd

def str2time(x):
    try:
        return datetime.datetime.strptime(x, '%m/%d/%Y %I:%M:%S %p')
    except:
        return pd.NaT

df1_new['obs_date'] = df1_new['obs_date'].apply(str2time)
print(df1_new)
     person_id             obs_date
0          1  2377-07-23 12:00:00
1          1                  NaT
2          3                  NaT
3          3  2277-07-27 12:00:00
4          5  2077-07-13 12:00:00
5          5                  NaT

将字符串date转换为datetime,然后再转换回所需的格式。示例如下:

from datetime import datetime
d = "7/23/2377 12:00:00 AM"
datetime.strptime(d, "%m/%d/%Y %I:%M:%S %p").strftime("%Y-%m-%d %H:%M:%S %p")

#output
>>>'2377-07-23 00:00:00 AM'
from datetime import datetime

def convert_func(x):
    return datetime.strptime(x, "%m/%d/%Y %I:%M:%S %p").strftime("%Y-%m-%d %H:%M:%S")

df1_new['obs_date'] = df1_new['obs_date'].astype(str)
df1_new['obs_date'] = df1_new['obs_date'].apply(convert_func)

这应该管用

相关问题 更多 >