In python how to generate date in utc/gmt?

Viewed 121

I am using dateutil.parser to generate a random date, it seem to be in my local timezone, how do I generate it in UTC/GMT?

from dateutil import parser
new_date = str(random.randint(1,27))+"/"+str(random.randint(1,12))+"/"+str(random.randint(2001,2020)) #d/m/y
targetdate = parser.parse(new_date, dayfirst=True)
2 Answers

Probably the easiest way to do this is to use datetime directly, rather than trying to parse a string you generate.

import datetime
import random

def generate_random_date(from=datetime.datetime(month=1, day=1, year=2001),
                         to=datetime.datetime(month=1, day=1, year=2021)):
    from_t, to_t = from.timestamp(), to.timestamp()
    gen = random.randint(int(from_t), int(to_t))
    return datetime.datetime.utcfromtimestamp(gen).date()

try this:

import pytz
from datetime import datetime
utc_current_datetime = datetime.now(pytz.timezone("UTC"))
print(utc_current_datetime)

this returns the time in UTC which prints 2021-05-03 03:38:45.652857+00:00

alternatively you can use the time module like so:

from datetime import datetime, timezone
utc_current_datetime = datetime.now(timezone.utc)
print(utc_current_datetime)

also UTC which prints 2021-05-03 03:38:45.652857+00:00

if you just want the date from this, you can use

utc_current_datetime.date()

The time module has many other functions that can help you. Take a look at the time documentation and DateTime documentation for more information

Related