How do I get a string format of the current date time, in python?

PythonDatetime

Python Problem Overview


For example, on July 5, 2010, I would like to calculate the string

 July 5, 2010

How should this be done?

Python Solutions


Solution 1 - Python

You can use the datetime module for working with dates and times in Python. The strftime method allows you to produce string representation of dates and times with a format you specify.

>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'July 23, 2010'
>>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
'10:36AM on July 23, 2010'

Solution 2 - Python

#python3

import datetime
print(
    '1: test-{date:%Y-%m-%d_%H:%M:%S}.txt'.format( date=datetime.datetime.now() )
    )

d = datetime.datetime.now()
print( "2a: {:%B %d, %Y}".format(d))

# see the f" to tell python this is a f string, no .format
print(f"2b: {d:%B %d, %Y}")

print(f"3: Today is {datetime.datetime.now():%Y-%m-%d} yay")

#4: to make the time timezone-aware pass timezone to .now()
tz = datetime.timezone.utc
ft = "%Y-%m-%dT%H:%M:%S%z"
t = datetime.datetime.now(tz=tz).strftime(ft)
print(f"4: timezone-aware time: {t}")

1: test-2018-02-14_16:40:52.txt

2a: March 04, 2018

2b: March 04, 2018

3: Today is 2018-11-11 yay

4: timezone-aware time: 2022-05-05T09:04:24+0000


Description:

Using the new string format to inject value into a string at placeholder {}, value is the current time.

Then rather than just displaying the raw value as {}, use formatting to obtain the correct date format.

https://docs.python.org/3/library/string.html#formatexamples

https://docs.python.org/3/library/datetime.html

Solution 3 - Python

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%B %d, %Y")
'July 23, 2010'

Solution 4 - Python

If you don't care about formatting and you just need some quick date, you can use this:

import time
print(time.ctime())

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - PythonDave WebbView Answer on Stackoverflow
Solution 2 - PythonPieterView Answer on Stackoverflow
Solution 3 - PythonPär WieslanderView Answer on Stackoverflow
Solution 4 - PythonscopeView Answer on Stackoverflow