Get a datetime format from a string in Python - 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'

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.

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

Related

Extraction of day, month and year from the date 4.5.6

Which function can I use to extract day, month and year from dates written in this manner 4.5.6 where 4 is the day, 5 is the month and 6 is the year (presumably 2006). I have already tried using dateparser.parse but it is not working.
day, month, year = map(int, '4.5.6'.split('.'))
And then add 2000 as necessary to the year.
You can then construct a datetime object with
from datetime import datetime
dt = datetime(year, month, day)
While it would be logical to use datetime.strptime, the one-digit year messes things up, and the above will just work fine.
Here is how you can use the datetime.datetime.strptime() method:
import datetime
s = "4.5.6"
i = s.rindex('.') + 1
s = s[:i] + s[i:].rjust(2, '0') # Add padding to year
dt = datetime.datetime.strptime(s, "%d.%m.%y")
print(dt)
Output:
2006-05-04 00:00:00
With the resulting datetime.datetime object, you can access plenty of information about the date, for example you can get the year by printing dt.year (outputs 2006).

Create list with days of month

Hi everyone!
I'm trying to generate list with dates of current month, but it generates wrong: from 2nd january to 1st february, I need list starts from 1st day of current month to last - 1 to 31, for example.
I have already searched the site and on Google, but so far I have not found anything. What am I doing wrong?
import datetime
year = 2021
month = 1
my_date = datetime.date(year, month, 1)
delta = datetime.timedelta(days=1)
dates = []
while my_date.month == month:
dates.append((my_date + delta).strftime('%d-%b-%Y'))
my_date += delta
print(dates)
print(len(dates))
That's because you are adding the date delta twice. Remove the first delta addition:
import datetime
year = 2021
month = 1
my_date = datetime.date(year, month, 1)
delta = datetime.timedelta(days=1)
dates = []
while my_date.month == month:
dates.append((my_date).strftime('%d-%b-%Y'))
my_date += delta
print(dates)
print(len(dates))
Output:
>>> print(dates)
['01-Jan-2021', '02-Jan-2021', '03-Jan-2021', '04-Jan-2021', '05-Jan-2021', '06-Jan-2021', '07-Jan-2021', '08-Jan-2021', '09-Jan-2021', '10-Jan-2021', '11-Jan-2021', '12-Jan-2021', '13-Jan-2021', '14-Jan-2021', '15-Jan-2021', '16-Jan-2021', '17-Jan-2021', '18-Jan-2021', '19-Jan-2021', '20-Jan-2021', '21-Jan-2021', '22-Jan-2021', '23-Jan-2021', '24-Jan-2021', '25-Jan-2021', '26-Jan-2021', '27-Jan-2021', '28-Jan-2021', '29-Jan-2021', '30-Jan-2021', '31-Jan-2021']
>>> print(len(dates))
31

How to handle date error with months in datetime.replace in python?

I have the date object which is as follows. Date: 2025-11-30. If I add 3 month to it using following code, it will raise an Exception as follows.
code:
def get_next_n_month_forward(date, n):
if date.month + n > 12:
next_month = date.replace(year=date.year + 1,
month=(date.month + n) % 12)
else:
next_month = date.replace(month=(date.month + n))
return next_month
exception:
ValueError: day is out of range for month
As far as I can understand from error it is because february does not have 30th day.
Question: How can I make it set to the last day of the month? !Note: In my case it would be 29th or 28th of February.
You can use timedelta object to increase and decrease dates
from datetime import timedelta
import datetime
d = datetime.datetime.today()
new_d = d + timedelta(days=1)
In order to set the date to the last day of month, you can set the date to the 1st of the next month and then decrease it by 1 day:
from datetime import timedelta
import datetime
day = datetime.datetime.today()
prev_month_last_day = day.replace(day=1) - timedelta(days=1)

Generate dates for a particular month?

is there any way to generate all the dates of a particular month when the month and year are inputted?
I have
daterange = date_range(date1, date2)
dates=[]
for x in daterange:
dates.append((x.strftime('%Y-%m-%d')))
using pandas, but how can I account for different month lengths?
You could use pd.offsets.MonthBegin and then use an end exclusive daily date range:
dts = pd.date_range(month_start, month_start + pd.offsets.MonthBegin(1), closed="left")
I find I can't import calendar on my system, so here's a datetime-only solution:
from datetime import date, timedelta
month, year = 2, 2008
day = timedelta(days=1)
date1 = date(year, month, 1)
dates = []
d = date1
while d.month == month:
dates.append(d)
d += day
(Creates a list of the dates of days in February 2008, a leap year). If you want string representations of the dates, you can use:
from datetime import timedelta, datetime
month, year = 2, 2008
day = timedelta(days=1)
date1 = datetime(year, month, 1)
d = date1
dates = []
while d.month == month:
dates.append(d.strftime('%Y-%m-%d'))
d += day
You can do that with the calendar module:
import calendar
date_of_first_weekday, number_days_in_month = calendar.monthrange(year, month)
The calendar module has all you need:
import calendar
first_weekday, month_days = calendar.monthrange(year, month)
for mday in xrange(1, month_days + 1):
print mday

Get month by week, day and year

I want to know how you get the months by the giving day, week number and year.
For example if you have something like this
def getmonth(day, week, year):
# by day, week and year calculate the month
print (month)
getmonth(28, 52, 2014)
# print 12
getmonth(13, 42, 2014)
# print 10
getmonth(6, 2, 2015)
# print 1
Per interjay's suggestion:
import datetime as DT
def getmonth(day, week, year):
for month in range(1, 13):
try:
date = DT.datetime(year, month, day)
except ValueError:
continue
iso_year, iso_weeknum, iso_weekday = date.isocalendar()
if iso_weeknum == week:
return date.month
print(getmonth(28, 52, 2014))
# 12
print(getmonth(13, 42, 2014))
# 10
print(getmonth(6, 2, 2015))
# 1
You can do it with the isoweek module, something like this for your first example:
from isoweek import Week
w = Week(2014, 52)
candidates = [date for date in w.days() if date.day == 28]
assert len(candidates) == 1
date = candidates[0] # your answer
I'm using python-dateutil when I need to implement some tricky date operations.
from datetime import date
from dateutil.rrule import YEARLY, rrule
def get_month(day, week, year):
rule = rrule(YEARLY, byweekno=week, bymonthday=day, dtstart=date(year, 1, 1))
return rule[0].month
from datetime import datetime, timedelta
def getmonth(day, week, year):
d = datetime.strptime('%s %s 1' % (week-1, year), '%W %Y %w')
for i in range(0, 7):
d2 = d + timedelta(days=i)
if d2.day == day:
return d2.month

Categories

Resources