Convert python datetime to epoch with strftime

前端 未结 8 2314
执念已碎
执念已碎 2020-11-22 10:15

I have a time in UTC from which I want the number of seconds since epoch.

I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an exa

相关标签:
8条回答
  • 2020-11-22 10:49
    import time
    from datetime import datetime
    now = datetime.now()
    
    time.mktime(now.timetuple())
    
    0 讨论(0)
  • 2020-11-22 10:49
    import time
    from datetime import datetime
    now = datetime.now()
    
    # same as above except keeps microseconds
    time.mktime(now.timetuple()) + now.microsecond * 1e-6
    

    (Sorry, it wouldn't let me comment on existing answer)

    0 讨论(0)
  • 2020-11-22 10:59

    I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).

    >>> import datetime
    >>> import calendar
    >>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
    >>> calendar.timegm(aprilFirst.timetuple())
    1333238400
    
    0 讨论(0)
  • 2020-11-22 11:00

    This works in Python 2 and 3:

    >>> import time
    >>> import calendar
    >>> calendar.timegm(time.gmtime())
    1504917998
    

    Just following the official docs... https://docs.python.org/2/library/time.html#module-time

    0 讨论(0)
  • 2020-11-22 11:03

    if you just need a timestamp in unix /epoch time, this one line works:

    created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
    >>> created_timestamp
    1522942073L
    

    and depends only on datetime works in python2 and python3

    0 讨论(0)
  • 2020-11-22 11:03

    For an explicit timezone-independent solution, use the pytz library.

    import datetime
    import pytz
    
    pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()
    

    Output (float): 1333238400.0

    0 讨论(0)
提交回复
热议问题