2

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())

5
  • 2
    possibly duplicate of How to get UTC time in Python Commented Feb 5, 2018 at 12:02
  • This: time.asctime(time.gmtime()) Commented Feb 5, 2018 at 12:04
  • 2
    Possible duplicate of How do I convert local time to UTC in Python? Commented Feb 5, 2018 at 12:04
  • @khelwood that worked. Thank you! Commented Feb 5, 2018 at 12:08
  • @astro No problem. I've posted it as an answer, below. Commented Feb 5, 2018 at 12:10

4 Answers 4

4

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'
Sign up to request clarification or add additional context in comments.

1 Comment

looks better one
1

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'

2 Comments

pandas might be a bit overkill here. You can just use str(utc) to get a string
@Farhan.K, noted / updated. Only used pandas because it formats nicely without losing structure.
1
import datetime
print(datetime.datetime.utcnow())

2018-02-05 12:05:53.329809

Comments

1

Below is the code where you can select any timezone:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.