Karan Sharma

Converting UTC to Local Time in Python

1 minutes (316 words)

Often I’ve felt the need to convert UTC time to IST but a quick google search reveals some shitty websites which makes such a seemingly simple task irritating and difficult. I tried to search for any small scripts or tools but thought I can whip one up real quick in Python and use it locally for myself.

Here’s the script I wrote, you can customise according to your needs if you wish to:

import argparse
import time
from datetime import datetime
from sys import exit

from dateutil.parser import parse

def datetime_from_utc_to_local(utc_datetime):
    now = time.time()
    offset = datetime.fromtimestamp(now) - datetime.utcfromtimestamp(now)
    return utc_datetime + offset

parser = argparse.ArgumentParser(description="Convert UTC time to Local time.")
    "--timestamp", required=True, help="timestamp of UTC string"

args = parser.parse_args()

    utc = parse(args.timestamp)
except Exception as e:

res = datetime_from_utc_to_local(utc)


It takes a --timestamp parameter which should be a string depicting the UTC time format.


ist: aliased to python /home/karan/Code/Infra/utc-ist/utc-ist.py --timestamp

$ ist 3:45

Tags: #Python