How do i convert the following timestamp(contains utc time) in string to epoch time in python2.6?

How do i convert the following timestamp(contains utc time) in string ('2019-08-01T11:02:28-07:00') to epoch time in python2.6?

Thanks in advance

Upvotes: 0

Views: 60

Answers (1)

user5386938
user5386938

Reputation:

Something like this?

import datetime

FMT = '%Y-%m-%dT%H:%M:%S%z'
s = '2019-08-01T11:02:28-07:00'
dt = datetime.datetime.strptime(s, FMT)
print(dt.timestamp())

For python 2.7:

from datetime import datetime, timedelta, tzinfo

FMT = '%Y-%m-%dT%H:%M:%S'

ZERO = timedelta(0)
HOUR = timedelta(hours=1)

# A UTC class.

class UTC(tzinfo):
    """UTC"""

    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

utc = UTC()
_EPOCH = datetime(1970, 1, 1, tzinfo=utc)

def getTZ(s):
    sign, s = s[:1], s[1:]
    h, m = map(int, s.split(':'))
    total_minutes = h*60+m
    total_minutes *= -1 if sign=='-' else 1
    offset = timedelta(minutes=total_minutes)

    class MyTZ(tzinfo):
        def utcoffset(self, dt):
            return offset

        def dst(self, dt):
            return timedelta(0)

    return MyTZ()

s = '2019-08-01T11:02:28-07:00'
tz = getTZ(s[-6:])
dt = datetime.strptime(s[:-6], FMT)
dt = dt.replace(tzinfo=tz)
print(s)
print(dt.isoformat())
#print(dt.timestamp()) # New in version 3.3
print((dt-_EPOCH).total_seconds())

See strptime. You may also want to look at pytz.

Forgot that you wanted epoch time. Here's one solution.

Upvotes: 1

Related Questions