How to convert current date to epoch timestamp?

前端 未结 9 2288
情话喂你
情话喂你 2020-12-14 05:41

How to convert current date to epoch timestamp ?

Format current date:

29.08.2011 11:05:02
相关标签:
9条回答
  • 2020-12-14 05:49

    I think this answer needs an update and the solution would go better this way.

    from datetime import datetime
    
    datetime.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S").strftime("%s")
    

    or you may use datetime object and format the time using %s to convert it into epoch time.

    0 讨论(0)
  • 2020-12-14 05:53

    if you want UTC try some of the gm functions:

    import time
    import calendar
    
    date_time = '29.08.2011 11:05:02'
    pattern = '%d.%m.%Y %H:%M:%S'
    utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
    print utc_epoch
    
    0 讨论(0)
  • 2020-12-14 06:00
    from time import time
    >>> int(time())
    1542449530
    
    
    >>> time()
    1542449527.6991141
    >>> int(time())
    1542449530
    >>> str(time()).replace(".","")
    '154244967282'
    

    But Should it not return ?

    '15424495276991141'
    
    0 讨论(0)
  • 2020-12-14 06:01

    That should do it

    import time
    
    date_time = '29.08.2011 11:05:02'
    pattern = '%d.%m.%Y %H:%M:%S'
    epoch = int(time.mktime(time.strptime(date_time, pattern)))
    print epoch
    
    0 讨论(0)
  • 2020-12-14 06:02

    Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

    So, you need to do below

    >>> import time, os
    >>> d='2014-12-11 00:00:00'
    >>> p='%Y-%m-%d %H:%M:%S'
    >>> epoch = int(time.mktime(time.strptime(d,p)))
    >>> epoch
    1418236200
    >>> os.environ['TZ']='UTC'
    >>> epoch = int(time.mktime(time.strptime(d,p)))
    >>> epoch
    1418256000
    
    0 讨论(0)
  • Use strptime to parse the time, and call time() on it to get the Unix timestamp.

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