Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print current time in Python 3

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

2 Answers

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
like image 83
Life is complex Avatar answered Jul 15 '26 06:07

Life is complex


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'                                                                                                   
like image 28
AK47 Avatar answered Jul 15 '26 06:07

AK47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!