-2

I have following code that gives output as "2020-07-30 15:59:17.535228", I would like to convert it from datetime into year and month format "20JUL" using python

I understand this is possible, I tried all possible changes but each time I'm getting some or other error...

Can you please guide..

Desired Output of below Python Code

20JUL 

Python Code

from datetime import datetime
from dateutil.relativedelta import relativedelta, TH

todayte = datetime.today()
cmon = todayte.month

for i in range(1, 6):
    t = todayte + relativedelta(weekday=TH(i))
    if t.month != cmon:
        # since t is exceeded we need last one  which we can get by subtracting -2 since it is already a Thursday.
        t = t + relativedelta(weekday=TH(-2))
        break
import datetime
print(t)
thu = datetime.datetime.strptime('%Y-%m-%d %H:%M:%S.%f').strftime(date, '%Y-%m-%d')
print(thu)

The Code is giving following error

2020-07-30 15:59:17.535228
Traceback (most recent call last):
  File "NextExpiryDatetry.py", line 138, in <module>
    tame = datetime.datetime.strptime('%Y-%m-%d %H:%M:%S.%f').strftime(date, '%Y%M')
TypeError: strptime() takes exactly 2 arguments (1 given)
  • Read about [`datetime.strptime`](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime) works. – sushanth Jul 23 '20 at 10:48
  • 1
    `thu = todayte.strftime("%y%b")` – DD_N0p Jul 23 '20 at 10:50
  • Does this answer your question? [Convert datetime object to a String of date only in Python](https://stackoverflow.com/questions/10624937/convert-datetime-object-to-a-string-of-date-only-in-python) – above_c_level Jul 23 '20 at 11:07

2 Answers2

0
from datetime import datetime
from dateutil.relativedelta import relativedelta, TH

todayte = datetime.today()
cmon = todayte.month

for i in range(1, 6):
    t = todayte + relativedelta(weekday=TH(i))
    if t.month != cmon:
        # since t is exceeded we need last one  which we can get by subtracting -2 since it is already a Thursday.
        t = t + relativedelta(weekday=TH(-2))
        break
import datetime
print(t)
thu = todayte = datetime.today().strftime("%y%b")
print(thu)

This must give required output

RahulN
  • 218
  • 1
  • 5
0
from datetime import datetime

now = datetime.now()
month = now.month
day = now.day

# a list so you can easily index it
months = [
    "JAN",
    "FEB",
    "MAR",
    "APR",
    "MAY",
    "JUN",
    "JUL",
    "AUG",
    "SEP",
    "OCT",
    "NOV",
    "DEC"
]
print(
    str(day) + months[month - 1] # -1 since the Index starts at 0
)
Dharman
  • 30,962
  • 25
  • 85
  • 135
12ksins
  • 307
  • 1
  • 12