将python列中以毫秒表示的字符串时间转换为时间戳

2024-04-20 10:18:33 发布

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

我在数据帧(“df”)中有一列(“arrival\u time”),它包含格式为“H:M:S:f”(f-->;毫秒)的时间字符串值。有些只有“H:M:S”,因此整个列的格式不一致。你知道吗

我试着转换成时间戳来获得字符串时间的数字表示。你知道吗

样本数据:

0          20:43:09:01
1          06:00:16
2          06:30:21
3          07:00:03
4          06:32:43
5          07:33:31
6          07:37:39:09
7          07:49:01
8          08:52:05
9          08:29:44:10
import time
import datetime

def conv_date(myDate):
    try:
        if str(myDate).count(":") == 3:
            dt = datetime.datetime.strptime(myDate,'%H:%M:%S,%f').timestamp()
        else:
            dt = datetime.datetime.strptime(myDate,'%H:%M:%S').timestamp()
    except:
        return float('NaN')
    return dt

# some values are data type 'float' so converted everything to string
df["arrival_time"] = df["arrival_time"].astype(str).apply(conv_date)

Output:
0         -2.208885e+09
1         -2.208938e+09
2         -2.208937e+09
3         -2.208935e+09
4         -2.208936e+09
5         -2.208933e+09

当我期望一个正值时,我得到一个负的时间戳。你知道吗


Tags: 数据字符串importdfdatetimedatetime格式
1条回答
网友
1楼 · 发布于 2024-04-20 10:18:33

尝试用数据附加当前日期并使用以下命令:

p = pd.to_datetime("2019-04-22 05:03:35",format='%Y-%m-%d %H:%M:%S.%f')
p.timestamp()
1555909415.0

p = pd.to_datetime("2019-04-22 05:03:35.74",format='%Y-%m-%d %H:%M:%S.%f')
p.timestamp()
1555909415.74

您可以这样附加当前日期:

df.date = df.date.apply(lambda x: datetime.now().date().strftime("%Y-%m-%d") + " " + x)

将其应用于整个数据帧的方法是:

df["event_timestamp"] = pd.to_datetime(df["event_timestamp"], format='%Y-%m-%d %H:%M:%S.%f')

相关问题 更多 >