How do you find the previous month in YYYY/MM Format - python

It's quite simple. I like to find the previous month for the current time, but in YYYY/MM Date Format. Ideally using Datetime.

Use months with relativedelta:
>>> from dateutil.relativedelta import relativedelta
>>> (datetime.now() - relativedelta(months=1)).strftime('%Y/%m')
'2019/08'
This covers the case you said:
>> (datetime.strptime('01/03/2019', '%d/%m/%Y') - relativedelta(months=1)).strftime('%Y/%m')
'2019/02'

from datetime import datetime, timedelta
(datetime.now() - timedelta(days=30)).strftime('%Y/%m')
This may suffice depending on your needs, a more sophisticated approach may use libraries from pip, like dateutil
from dateutil.relativedelta import relativedelta
(datetime.now() - relativedelta(months=1)).strftime('%Y/%m')
Regards

Using only the datetime module from the standard library, we can get the month and year from 15 days before the start of our month:
from datetime import date, timedelta
def previous_month():
format = '%Y/%m'
d = date.today().replace(day=1) # first day of the month
return date.strftime(d-timedelta(days=15), format) # 15 days earlier is in the previous month
previous_month()
# '2019/08

Related

Is there a function in python that could generate date 4 weeks from current date/given date?

Is there any function in python that can generate date for example 4 weeks from now or given date?
I've gone through documentation from datetime modeule but couldnt find any example that can support my question.
four_weeks = datetime.timedelta(days=4*7)
dt = datetime.datetime.now()
print(dt + four_weeks)
Here you go:
from datetime import timedelta
from datetime import datetime
today = datetime.today()
print(today + timedelta(weeks=1))
I think the thing you're looking for is timedelta.
from datetime import timedelta
def add_weeks(dt, n_weeks):
n_days = 7 * n_weeks
return dt + timedelta(days=n_days)
In python datetime module has a class called datetime which represents a date + time, an point on time line. There is another class called timedelta that represents difference between two dates (datetiems).
You can add a date with a timedelta.
example code:
from datetime import datetime, timedelta
now = datetime.now()
duration = timedelta(days=28)
target = now + duration
print(target)

Python : Is there a way to get the names of last three Month Names?

How can I extract last three month names in Python? If I am running this today then I would like to see May, June and July as my result.
Easier way is to use "%B" using datetime and timedelta
from dateutil.relativedelta import relativedelta
from datetime import datetime
today = datetime.now()
for i in range(1,4):
print((today - relativedelta(months=i)).strftime('%B'))
Output:
July
June
May
One way is to use the python calendar module, and list slice a month name for a given, extracted datetime month.
.month_name returns a list of all the month names.
calendar is part of the standard library.
For timedelta, there isn't a month parameter because the length of a month is not a constant value, so use days, as an approximation.
See datetime for the available methods.
datetime is part of the python standard library, so doesn't require a separate installation.
Use .month to extract the month from the datetime.
from datetime import datetime, timedelta
import calendar
# get the time now
now = datetime.now()
# iterate through 3 different timedeltas as an example
for x in range(1, 4):
new = now - timedelta(days=31*x)
print(calendar.month_name[new.month])
[out]:
July
June
May
As mentioned in the answer by bigbounty, using .strftime with '%B' is a better option than using calendar
However, unlike the dateutil module, timedelta still doesn't have a month parameter.
The dateutil module provides powerful extensions to the standard datetime module and must be installed, and then imported.
# get the time now
now = datetime.now()
# iterate through 3 different timedeltas as an example
for x in range(1, 4):
new = now - timedelta(days=31*x)
print(new.strftime('%B'))
[out]:
July
June
May
Best way to do this is a combination of the date and calendar modules.
date.today().month will give you a numerical value for the current month (1-12)
calendar.month_name[x] will give you the name for the month represented by the number x
the % operator will be used to wrap around the index of the month_name object to avoid the pesky 0 index returning ''
Putting them together we have:
from datetime import date
from calendar import month_name
def previous_n_months(n):
current_month_idx = date.today().month - 1 # Value is now (0-11)
for i in range(1, n+1):
# The mod operator will wrap the negative index back to the positive one
previous_month_idx = (current_month_idx - i) % 12 #(0-11 scale)
m = int(previous_month_idx + 1)
print(month_name[m])
Example usage:
>>> previous_n_months(3)
July
June
May

Subtract a year from given date (not current time) in python

I have a file in which date field in YYYYMMDD format. I need to pick that date and product to join with another file by subtracting 12 months to get other information.
File1
20180131,Apple
20180228,Orange
20180331,Grapes
File2
20170131,Apple,45
20170131,Orange,20
20170228,Orange,35
20170331,Apple,25
Output
20180131,Apple,45
20180228,Orange,35
20180331,Grapes,null
How to subtract 12 months or 1 year from given date(yyyymmdd) and get the answer in the same format.
You can use strptime from the standard library to parse the date, but unfortunately there is no calendar support in the standard library so you have to use the dateutil library to subtract the year.
import datetime
from dateutil.relativedelta import relativedelta
d = datetime.datetime.strptime('20180131', '%Y%m%d').date()
print((d - relativedelta(years=1)).strftime('%Y%m%d'))
This will print 20170131.
Note that if the input is e.g. 20160229, this will print out 20150228. I'm not sure exactly what the semantics of relativedelta are so be sure to read the docs if this is important to you.
Why not timedelta?
The datetime.timedelta is not appropriate and does not work correctly. A timedelta represents a duration in time, or it represents a number of days, but counter-intuitively, a year is not a duration but instead a calendrical concept. A year is either 365 or 366 days, depending on which year.
It becomes pretty obvious that timedelta will not work once you find the correct test cases:
In [1]: from datetime import date, timedelta
In [2]: date(2018, 1, 1) - timedelta(365)
Out[2]: datetime.date(2017, 1, 1)
In [3]: date(2017, 1, 1) - timedelta(365)
Out[3]: datetime.date(2016, 1, 2)

How to use ftplib in Python to change directories when directory name matches a date [duplicate]

I need to find "yesterday's" date in this format MMDDYY in Python.
So for instance, today's date would be represented like this:
111009
I can easily do this for today but I have trouble doing it automatically for "yesterday".
Use datetime.timedelta()
>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(days=1)
>>> yesterday.strftime('%m%d%y')
'110909'
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%m%d%y')
This should do what you want:
import datetime
yesterday = datetime.datetime.now() - datetime.timedelta(days = 1)
print yesterday.strftime("%m%d%y")
all answers are correct, but I want to mention that time delta accepts negative arguments.
>>> from datetime import date, timedelta
>>> yesterday = date.today() + timedelta(days=-1)
>>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses
Could I just make this somewhat more international and format the date according to the international standard and not in the weird month-day-year, that is common in the US?
from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
yesterday.strftime('%Y-%m-%d')
To expand on the answer given by Chris
if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know
>>> from datetime import date, timedelta
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'
If you want it as an integer (which can be useful)
>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817

Parse a date in a specific timezone with Python

How can I take this date string:
"2015-01-01"
and, assuming it is in a specific timezone (say, "US-Mountain"), convert it to a POSIX timestamp?
Like so:
magic_parse_function("2015-01-01", pytz.timezone("US-Mountain")) -> 1420095600
I've spent quite some time scouring the docs and this site, playing with aware/unaware datetime objects, and am hoping for a not-too-crazy solution. The following does not work, the last two lines of output are identical, and they should be 3600 seconds apart:
import datetime
import time
import pytz
timestring = "2015-01-01"
pacific = pytz.timezone("US/Pacific")
mountain = pytz.timezone("US/Mountain")
(year, month, day) = timestring.split('-')
year = int(year)
month = int(month)
day = int(day)
unaware = datetime.datetime(year, month, day, 0, 0, 0, 0)
# aware_pacific = pacific.localize(unaware)
# aware_mountain = mountain.localize(unaware)
aware_mountain = unaware.replace(tzinfo=mountain)
aware_pacific = unaware.replace(tzinfo=pacific)
print time.mktime(aware_pacific.timetuple())
print time.mktime(aware_mountain.timetuple())
There are three steps:
Convert the date string into a naive datetime object:
from datetime import datetime
dt = datetime(*map(int ,'2015-01-01'.split('-')))
Get a timezone-aware datetime object:
import pytz # $ pip install pytz
aware = pytz.timezone("US/Mountain").localize(dt, is_dst=None)
is_dst=None raises an exception for ambiguous or non-existing times. Here're more details about what is is_dst flag and why do you need it, see "Can I just always set is_dst=True?" section
Get POSIX timestamp:
timestamp = aware.timestamp()
.timestamp() is available since Python 3.3+. See multiple solutions for older Python versions.

Categories

Resources