I have a value like this:
var="11-feb-15:04:02:21"
I need to convert to epoch time:
I tried this:
var.strftime('%s')
I get this error:
AttributeError: 'str' object has no attribute 'strftime'
Any ideas? I
I have a value like this:
var="11-feb-15:04:02:21"
I need to convert to epoch time:
I tried this:
var.strftime('%s')
I get this error:
AttributeError: 'str' object has no attribute 'strftime'
Any ideas? I
I hope you will go through this example and look up the corresponding documentation.
>>> s = "11-feb-15:04:02:21"
>>> timestruct = time.strptime(s, "%d-%b-%y:%H:%M:%S")
>>> time.mktime(timestruct)
1423623741.0
The format specifiers are defined here: https://docs.python.org/2/library/time.html#time.strftime
The docs are also clear on the fact that when you want to convert from struct_time in local time to seconds since the epoch you need to use mktime()
.
To convert a time string that represents local time into "seconds since the Epoch":
#!/usr/bin/env python
import time
from datetime import datetime
import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal
tt = time.strptime("11-feb-15:04:02:21", "%d-%b-%y:%H:%M:%S")
naive_dt = datetime(*tt[:5]+(min(tt[5], 59),))
dt = get_localzone().localize(naive_dt, is_dst=None)
timestamp = (dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()
print(timestamp) # -> 1423623741.0
This solution raises an exception if the input time is ambiguous or non-existent e.g., during a DST transition -- set is_dst
parameter to True/False to disambiguate the time and/or call tz.normalize()
method to adjust non-existent local times.
To get a proper utc offset, the tz database is used (get_localzone()
returns the local timezone as a pytz
timezone object).
time.strptime()
is used to support leap seconds e.g., "1-jul-15:1:59:60"
is converted to datetime(2015, 7, 1, 1, 59, 59)
-- note: seconds are truncated to 59
.