0

Hello sorry for the ambiguous title, here's what I want to do :

I have a string:

month = '1406'

that corresponds to the month of June, 2014.

How can I dynamically say that that string represents the month of June and I specifically want the last day of the month.

So I want to write it in the format: '%Y-%m-%d %H:%M:%S' and have:

'2014-06-30 00:00:00'

2 Answers 2

2

You get the last day of a given month with the calendar.monthrange() function. Turn your string into two integers (month, year), create a datetime object from the year, month and last day of the month:

from datetime import datetime
from calendar import monthrange

year, month = int(month[:2]), int(month[2:])
year += 2000  # assume this century
day = monthrange(year, month)[1]

dt = datetime(year, month, day)  # time defaults to 00:00:00

Demo:

>>> from datetime import datetime
>>> from calendar import monthrange
>>> month = '1406'
>>> year, month = int(month[:2]), int(month[2:])
>>> year += 2000  # assume this century
>>> day = monthrange(year, month)[1]
>>> datetime(year, month, day)
datetime.datetime(2014, 6, 30, 0, 0)
>>> print datetime(year, month, day)
2014-06-30 00:00:00

The default string conversion for datetime objects fits your desired format already; you can make it explicit by calling str() on it or by using the datetime.datetime.isoformat() method, as you see fit.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, but I get : TypeError: 'module' object is not callable when I do datetime(year,month,day)
@salamey: Note that I imported from datetime import datetime. You must've done import datetime instead. In that case use dt = datetime.datetime(year, month, day)
0

This seems to do the trick:

import datetime

mon = '1406'
y, m = divmod(int(mon), 100)

dt = datetime.datetime(2000 + y + m // 12, m % 12 + 1, 1) - datetime.timedelta(days=1)
print dt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.