how set Month as string in Python datetime

Question:

I found this example how to set time and covert back to readable form

import datetime

x = datetime.datetime(2020, 5, 17)
print(x.strftime("%Y %b %d"))

My question is how to set new date with Month as string ?
Is it possible ? Is there some parameter/function for this ?

y = datetime.datetime(2020, May, 17)

Update:
How can I show difference between two times only in days ?

x = datetime.datetime(2024, 5, 17)
now=datetime.now()
print('Time difference:', str(x-now))

Current output is :
Time difference: 416 days, 9:37:06.470952

OK , I got it

print('Time difference:', (x-now).days)

Asked By: andrew

||

Answers:

There is no function provided which accepts a string argument to specify the month. But you can use the strptime class method to parse a string that contains a month name into a datetime value.

>>> from datetime import datetime
>>> datetime.strptime("2020 May 17", "%Y %b %d")
datetime.datetime(2020, 5, 17, 0, 0)

If you really need just the month as a string, and already have the other components as integers, you can parse just the month, extract the month number, and create a second object:

>>> year = 2020
>>> month = "May"
>>> day = 17
>>> datetime(year, datetime.strptime(month, "%b").month, day)

but I would recommend constructing a complete string first and parsing that.

datetime.strptime(f'{year} {month} {day}', "%Y %b %d")
Answered By: chepner

Using datetime.datetime.strptime() you can parse a month using the format codes:

  • %b for locale’s abbreviated name like Mar or
  • %B for locale’s full name like March or
  • %m for zero-padded decimal number like 03,

These format codes also apply to datetime.datetime.strftime().

Example:

from datetime import datetime

x = datetime.strptime("Mar","%b")

print(x.strftime("%m"))
Answered By: Max S.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.