Current Date time in a particular format Python

Viewed 2473

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.

3 Answers

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

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

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
Related