Björk Dongson
Björk Dongson

Reputation: 67

Change UTC offset for a time string

I would like to change the time to a manually chosen offset for a timestring In this example, I will subract 11 hours from the times, but the utc offset would still be 00:00.. How can I do this correctly?

    time = "2020-03-03T18:21:19+00:00"
    utc_diff = 2
    obj1 = datetime.datetime.strptime(
        re.sub(r"([\+-]\d\d):(\d\d)(?::(\d\d(?:.\d+)?))?", r"\1\2\3", time),
        "%Y-%m-%dT%H:%M:%S%z")
    obj1 = obj1 - datetime.timedelta(hours=-utc_diff)

Using this example the result would be

"2020-03-03T20:21:19+00:00"

But I want the offset to change also,:

"2020-03-03T20:21:19+02:00"

Upvotes: 0

Views: 33

Answers (2)

Ed Ward
Ed Ward

Reputation: 2331

This should work for your needs:

def utc_offset(time, offset):
    def pad(number):
        n = str(abs(number))

        while len(n) < 2:
            n = "0" + n

        if number >= 0:
            n = "+" + n
        else:
            n = "-" + n
        return n

    utc_diff_format = f"{pad(offset)}:00"

    time = list(time)
    i = time.index("+")
    time[i:] = list(utc_diff_format)
    time = ''.join(time)

    return time

time = "2020-03-03T18:21:19+00:00"
utc_diff = 2

print(utc_offset(time, utc_diff))

Output:

2020-03-03T18:21:19+02:00

Upvotes: 1

elisha robinson
elisha robinson

Reputation: 68

you can pass integer values directly to datetime.timedelta(hours=11)

Upvotes: 0

Related Questions