Convert datetime.datetime object to days since epoch in Python

后端 未结 3 1513
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 18:34

I\'ve got a pandas.Series object that might look like this:

import pandas as pd
myVar = pd.Series([\"VLADIVOSTOK 690090\", \"MAHE\", NaN, NaN, \         


        
相关标签:
3条回答
  • 2021-01-04 18:58
    myVar = pd.Series(["VLADIVOSTOK 690090", "MAHE", "NaN", "NaN", "VLADIVOSTOK 690090", "2000-07-01 00:00:00"])
    
    myVar[5] = pd.to_datetime(myVar[5]) - pd.datetime(1970,1,1)
    
    print(myVar)
    0     VLADIVOSTOK 690090
    1                   MAHE
    2                    NaN
    3                    NaN
    4     VLADIVOSTOK 690090
    5    11139 days 00:00:00
    dtype: object
    
    0 讨论(0)
  • 2021-01-04 19:00

    You can convert this to seconds since epoch first, then divide it out by the amount of seconds in a day (86,400 seconds in a day). Please note the integer division here - will not return a float.

    from datetime import datetime
    now = datetime.now()
    seconds = now.strftime("%s") # seconds since epoch
    days = int(seconds) / 86400 # days since epoch
    

    I added the import and now as an example of a datetime object I can play with.

    0 讨论(0)
  • 2021-01-04 19:01

    I'm not sure where you're getting 36,708 days since the epoch (it's only been 16,644 days since January 1, 1970), but datetime.timedelta objects (used in date arithmetic) have a days attribute:

    >>> import datetime
    >>> (datetime.datetime.utcnow() - datetime.datetime(1970,1,1)).days
    16644
    
    0 讨论(0)
提交回复
热议问题