在Python中将日期时间列转换为纪元 [英] Convert a column of datetimes to epoch in Python

查看:94
本文介绍了在Python中将日期时间列转换为纪元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在使用Python时遇到问题.我有一个Pandas DataFrame,其中一列是带有日期的字符串. 格式为:

I'm currently having an issue with Python. I have a Pandas DataFrame and one of the columns is a string with a date. The format is :

%Y-%m-%d%H:%m:00.000".例如:"2011-04-24 01:30:00.000"

"%Y-%m-%d %H:%m:00.000". For example : "2011-04-24 01:30:00.000"

我需要将整个列转换为整数.我尝试运行此代码,但是它非常慢,并且有几百万行.

I need to convert the entire column to integers. I tried to run this code, but it is extremely slow and I have a few million rows.

    for i in range(calls.shape[0]):
        calls['dateint'][i] = int(time.mktime(time.strptime(calls.DATE[i], "%Y-%m-%d %H:%M:00.000")))

你们知道如何将整列转换为纪元时间吗?

Do you guys know how to convert the whole column to epoch time ?

提前谢谢!

推荐答案

使用to_datetime将字符串转换为datetime,然后减去日期时间1970-1-1并调用dt.total_seconds():

convert the string to a datetime using to_datetime and then subtract datetime 1970-1-1 and call dt.total_seconds():

In [2]:
import pandas as pd
import datetime as dt
df = pd.DataFrame({'date':['2011-04-24 01:30:00.000']})
df

Out[2]:
                      date
0  2011-04-24 01:30:00.000

In [3]:
df['date'] = pd.to_datetime(df['date'])
df

Out[3]:
                 date
0 2011-04-24 01:30:00

In [6]:    
(df['date'] - dt.datetime(1970,1,1)).dt.total_seconds()

Out[6]:
0    1303608600
Name: date, dtype: float64

您可以看到,将此值转换回产生的时间是相同的:

You can see that converting this value back yields the same time:

In [8]:
pd.to_datetime(1303608600, unit='s')

Out[8]:
Timestamp('2011-04-24 01:30:00')

因此您可以添加新列或覆盖:

So you can either add a new column or overwrite:

In [9]:
df['epoch'] = (df['date'] - dt.datetime(1970,1,1)).dt.total_seconds()
df

Out[9]:
                 date       epoch
0 2011-04-24 01:30:00  1303608600

编辑

@Jeff建议的更好的方法:

better method as suggested by @Jeff:

In [3]:
df['date'].astype('int64')//1e9

Out[3]:
0    1303608600
Name: date, dtype: float64

In [4]:
%timeit (df['date'] - dt.datetime(1970,1,1)).dt.total_seconds()
%timeit df['date'].astype('int64')//1e9

100 loops, best of 3: 1.72 ms per loop
1000 loops, best of 3: 275 µs per loop

您还可以看到它明显更快

You can also see that it is significantly faster

这篇关于在Python中将日期时间列转换为纪元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆