1

What is the easiest way to convert current local time and date in format YYYY-MM-DD hh:mm:ss to UTC format in time package of Python? I'm using the following to obtain current time:

import time
time.strftime("%Y") + "-" + time.strftime("%m") + "-" + time.strftime("%d") + " " + time.strftime("%H") + ":" + time.strftime("%M") + ":" + time.strftime("%S")
  • 1
    Try this quick [Codecademy](http://www.codecademy.com/courses/python-beginner-en-zFPOx/0/1?curriculum_id=4f89dab3d788890003000096) lesson. – Malik Brahimi Jan 19 '15 at 21:01

1 Answers1

2

Use datetime.datetime instead of time:

 from datetime import datetime
 time = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Geotob
  • 2,847
  • 1
  • 16
  • 26
  • note: "local time" is `datetime.now()`. `datetime.utcnow()` returns utc time already. `.strftime()` does not convert local time to utc. It converts datetime object to string. – jfs Jan 20 '15 at 10:01
  • Yes @J.F.Sebastian, that's correct. My answer was based on the `time` example in the original question. – Geotob Jan 20 '15 at 18:57