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

时间:2019-05-10 03:55:51

标签: python dataframe datetime timestamp milliseconds

我在数据帧(“ df”)中有一列(“ arrival_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

当我期望一个正值时,我得到一个负时间戳。

1 个答案:

答案 0 :(得分:0)

尝试在当天添加数据并使用此数据:

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')
相关问题