Search code examples
pythondatetime-formatpython-datetime

Convert formatted date & time string to epoch time in Python


In python, I'd like to convert a formatted date + time + timezone string something like:

"Sat Jan 23 08:06:59 PST"

...to epoch time (or some other defineable format). I'm sure there is a simple way to do this that already exists, but after looking around in the datetime python library, I can't find exactly what I'm looking for. Any ideas on how this may be accomplished?


Solution

  • datetime.strptime(date_string, format) returns a datetime corresponding to date_string, parsed according to format. You can then use datetime.timestamp() to convert a datetime tuple to the epoch time. For example:

    from datetime import datetime
    
    datetime.timestamp(datetime.strptime('Sunday, September 26, 2010 at 8:35 PM', "%A, %B %d, %Y at %I:%M %p"))
    
    >>1285547700.0
    

    Not sure how to convert the timezone accurately.