salamey
salamey

Reputation: 3811

Get a datetime format from a string in Python

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'

Upvotes: 0

Views: 109

Answers (2)

gog
gog

Reputation: 11347

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

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121446

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.

Upvotes: 2

Related Questions