Convert python datetime to epoch with strftime

前端 未结 8 2319
执念已碎
执念已碎 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 11:09

    In Python 3.7

    Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat(). Specifically, this function supports strings in the format(s) YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where * can match any single character.

    https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

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

    If you want to convert a python datetime to seconds since epoch you could do it explicitly:

    >>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
    1333238400.0
    

    In Python 3.3+ you can use timestamp() instead:

    >>> datetime.datetime(2012,4,1,0,0).timestamp()
    1333234800.0
    

    Why you should not use datetime.strftime('%s')

    Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.

    >>> datetime.datetime(2012,04,01,0,0).strftime('%s')
    '1333234800'
    
    0 讨论(0)
提交回复
热议问题