5

I am a beginner in python and I have a function where I need to display the current date, time, month, year in the format, something similar to this.

Mon Jun 22 14:00:03 UTC 2020

I saw pre-defined datetime class but I am not sure how to utilize this class to derive the current date in this format (UTC).

Any help is much appreciated. Thanks in advance.

Ashwin krishnan
  • 117
  • 1
  • 9

3 Answers3

4

Is this what you're looking for?

from datetime import datetime, timezone
now = datetime.now(tz = timezone.utc)
print(now.strftime('%a %b %d %H:%M:%S %Z %Y'))

Output

Mon Jul 06 19:17:58 UTC 2020
Balaji Ambresh
  • 4,977
  • 2
  • 5
  • 17
  • 2
    this should be the preferred solution; utcnow is [kind of missleading](https://blog.ganssle.io/articles/2019/11/utcnow.html)... – FObersteiner Jul 07 '20 at 06:00
2

You can use datetime with strftime to get the desired result. You can do it as -

import datetime
date = datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y")
print(date)

Output :

Mon Jul 06 19:11:33 UTC 2020

Basically the syntax is - datetime.strftime(format) which will return a string representing date and time using date, time or datetime object. There are many format codes like %Y, %d, %m, etc which you can use to specify the format you want your result to be.

You can read more about them here

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
2

You can use an f-string.

Building on @Balaji Ambresh's answer:

from datetime import datetime, timezone
now = datetime.now(tz = timezone.utc)
print(f'{now:%a %b %d %H:%M:%S %Z %Y}')

Output

Mon Jul 06 19:17:58 UTC 2020
wjandrea
  • 28,235
  • 9
  • 60
  • 81
mherzog
  • 1,085
  • 1
  • 12
  • 24