Print current time in Python 3
19,731
Solution 1
Whats the problem? Your code works
λ python
Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2019-02-14 13:56:02'
>>> strftime("%H:%M:%S", gmtime())
'13:56:16'
>>>
EDIT:
This code works fine in terminal -- as @ForceBru mentioned, if you're running it in a script you will need to use the print function to display the result of strftime
from time import gmtime, strftime
print(strftime("%Y-%m-%d %H:%M:%S", gmtime()))
> '2019-02-14 13:56:02'
print(strftime("%H:%M:%S", gmtime()))
> '13:56:16'
Solution 2
Your original code was correct, but it was missing the print statement.
from time import gmtime, strftime
print (strftime("%Y-%m-%d %H:%M:%S", gmtime()))
# output
2019-02-14 14:56:18
Here are some other ways to obtain a Coordinated Universal Time (UTC) / Greenwich Mean Time (GMT) timestamp.
from datetime import datetime
from datetime import timezone
current_GMT_timestamp = datetime.utcnow()
print (current_GMT_timestamp)
# output
2019-02-14 14:56:18.827431
# milliseconds removed from GMT timestamp
reformatted_GMT_timestamp = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
print (reformatted_GMT_timestamp)
# output
2019-02-14 14:56:18
# GMT in ISO Format
current_ISO_GMT_timestamp = datetime.now(timezone.utc).isoformat()
print (current_ISO_GMT_timestamp)
# output
2019-02-14T14:56:18.827431+00:00
Related videos on Youtube
Author by
DeepSpace
BSc in Computer Science, Python developer for living and also has knowledge in C, C++, C# and Java.
Updated on June 04, 2022Comments
-
DeepSpace almost 2 years
Im having trouble trying to print the time on python. Here is the code that i recently tried:
from time import gmtime, strftime strftime("%Y-%m-%d %H:%M:%S", gmtime())
-
ForceBru about 5 yearsI mean, this code isn't printing anything, so you probably should use the
print
function -
Life is complex about 5 yearsFYI - Why is voting important? stackoverflow.com/help/why-vote -- Please select and answer that solves your question
-