How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

前端 未结 13 1456
臣服心动
臣服心动 2020-11-22 07:49

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.

How do I do this?

相关标签:
13条回答
  • 2020-11-22 07:56

    Here is a function I made based on the answer above

    def getDateToEpoch(myDateTime):
        res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
        return res
    

    You can wrap the returned value like this : str(int(res)) To return it without a decimal value to be used as string or just int (without the str)

    0 讨论(0)
  • 2020-11-22 07:57
    >>> import datetime
    >>> # replace datetime.datetime.now() with your datetime object
    >>> int(datetime.datetime.now().strftime("%s")) * 1000 
    1312908481000
    

    Or the help of the time module (and without date formatting):

    >>> import datetime, time
    >>> # replace datetime.datetime.now() with your datetime object
    >>> time.mktime(datetime.datetime.now().timetuple()) * 1000
    1312908681000.0
    

    Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html

    Documentation:

    • time.mktime
    • datetime.timetuple
    0 讨论(0)
  • 2020-11-22 07:58

    A bit of pandas code:

    import pandas
    
    def to_millis(dt):
        return int(pandas.to_datetime(dt).value / 1000000)
    
    0 讨论(0)
  • 2020-11-22 08:00

    It appears to me that the simplest way to do this is

    import datetime
    
    epoch = datetime.datetime.utcfromtimestamp(0)
    
    def unix_time_millis(dt):
        return (dt - epoch).total_seconds() * 1000.0
    
    0 讨论(0)
  • 2020-11-22 08:01

    In Python 3.3, added new method timestamp:

    import datetime
    seconds_since_epoch = datetime.datetime.now().timestamp()
    

    Your question stated that you needed milliseconds, which you can get like this:

    milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
    

    If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.

    0 讨论(0)
  • 2020-11-22 08:01

    Here's another form of a solution with normalization of your time object:

    def to_unix_time(timestamp):
        epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
        my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
        delta = my_time - epoch
        return delta.total_seconds() * 1000.0
    
    0 讨论(0)
提交回复
热议问题