0

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)

andrew
  • 459
  • 5
  • 21

2 Answers2

2

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"))
hc_dev
  • 8,389
  • 1
  • 26
  • 38
Max S.
  • 41
  • 3
  • 1
    Great explanation of *format codes* for moth and their usage. Hope you don't mind my improving edit. – hc_dev Mar 27 '23 at 18:12
1

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")
chepner
  • 497,756
  • 71
  • 530
  • 681