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

前端 未结 13 1495
臣服心动
臣服心动 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 08:08

    >>> import datetime
    >>> import time
    >>> import calendar
    
    >>> #your datetime object
    >>> now = datetime.datetime.now()
    >>> now
    datetime.datetime(2013, 3, 19, 13, 0, 9, 351812)
    
    >>> #use datetime module's timetuple method to get a `time.struct_time` object.[1]
    >>> tt = datetime.datetime.timetuple(now)
    >>> tt
    time.struct_time(tm_year=2013, tm_mon=3, tm_mday=19, tm_hour=13, tm_min=0, tm_sec=9,     tm_wday=1, tm_yday=78, tm_isdst=-1)
    
    >>> #If your datetime object is in utc you do this way. [2](see the first table on docs)
    >>> sec_epoch_utc = calendar.timegm(tt) * 1000
    >>> sec_epoch_utc
    1363698009
    
    >>> #If your datetime object is in local timeformat you do this way
    >>> sec_epoch_loc = time.mktime(tt) * 1000
    >>> sec_epoch_loc
    1363678209.0
    

    [1] http://docs.python.org/2/library/datetime.html#datetime.date.timetuple

    [2] http://docs.python.org/2/library/time.html

提交回复
热议问题