代码之家  ›  专栏  ›  技术社区  ›  Chubaka

在Python中将yyyy-mm-dd日期时间列转换为linux时间纪元

  •  1
  • Chubaka  · 技术社区  · 7 年前

    在python 3.6.0和pandas 0.20.0中

    有一个日期列yyy-mm-dd

    date
    2017-08-16
    2017-08-17
    2017-08-18
    

    这里有同样的问题

    Convert a column of datetimes to epoch in Python

    但不幸的是,这些解决方案都没有奏效

    df['date']=df['date'].astype('int64')//1e9
    
    ValueError: invalid literal for int() with base 10: '2017-08-16'
    
    
    df['date']=(df['date'] - dt.datetime(1970,1,1)).dt.total_seconds()
    
    NameError: name 'dt' is not defined
    

    有什么想法吗?谢谢您。

    3 回复  |  直到 7 年前
        1
  •  0
  •   user96564    7 年前

    试一试 pd.DateTimeIndex 乘以1000等于毫秒(如果你想在几秒钟内忽略乘法)

      df['Date'] = (pd.DatetimeIndex(df['Date']).astype(np.int64) // 10**9) * 1000
    
    print(df)
    
             Date
    1502841600000
    1502928000000
    1503014400000
    
        2
  •  0
  •   DM_Morpheus    7 年前

    您可以将其转换为 datetime 使用 timestamp()

    像这样的东西。

    from datetime import datetime
    
    s = '2017-08-16'
    epoch = datetime.strptime(s, "%Y-%m-%d").timestamp()
    print(epoch)
    # Output -- 1502821800.0
    
        3
  •  0
  •   Sagar Dawda    7 年前

    试试这个:

    from datetime import datetime as dt
    
    # String for the date
    s = '2017-08-16'
    
    #Convert string to datetime
    s_dt = dt.strptime(s, '%Y-%m-%d')
    
    #Initialize epoch
    epoch = dt.utcfromtimestamp(0)
    
    #Get your difference from epoch in ms
    linux_time = (s_dt - dt.utcfromtimestamp(0)).total_seconds()*1000
    
    #Your output
    linux_time
    1502841600000.0
    

    这是单个日期对象的代码。您可以创建一个函数并使用lambda将其应用于pandas列。

    希望这有帮助。