astro
astro

Reputation: 29

How do I retrieve UTC time in Python?

What would be the equivalent of time.ctime() for UTC time?

Currently, if I enter time.ctime() in the interpreter, I get this:

'Mon Feb  5 17:24:48 2018'

This returns the local time and I would like to know how to get time in the same format except in UTC.

Edit: It's time.asctime(time.gmtime())

Upvotes: 2

Views: 433

Answers (4)

khelwood
khelwood

Reputation: 59201

time.gmtime() returns an object representing the utctime.

To get it into the same format as time.ctime, you can use time.asctime().

>>> time.asctime(time.gmtime())
'Mon Feb  5 12:03:39 2018'

Upvotes: 4

gB08
gB08

Reputation: 182

Below is the code where you can select any timezone:

from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) 

Upvotes: 1

A_emperio
A_emperio

Reputation: 286

import datetime
print(datetime.datetime.utcnow())

2018-02-05 12:05:53.329809

Upvotes: 1

jpp
jpp

Reputation: 164793

This should work:

import datetime

utc = datetime.datetime.utcnow()
# datetime.datetime(2018, 2, 5, 12, 2, 56, 678723)

str(utc)
# '2018-02-05 12:05:10.617973'

Upvotes: 1

Related Questions