I have a date object like
Date = '202011'
This is yyyymm format.
I want to get the same month but n years prior. For example if n = 2, then I should get '201811'
Is there any function available to achieve this?
You can use the datetime module and dateutil library for this:
import datetime
from dateutil.relativedelta import relativedelta
fmt = '%Y%m'
date_string = '202011'
n = 2
# Parse `date_string` into a date object.
date = datetime.datetime.strptime(date_string, fmt).date()
# 2020-11-01
# Subtract `n` years.
new_date = date + relativedelta(years=-n)
# Output in the same format.
print(new_date.strftime(fmt)) # -> 201811
Related questions:
Python date string to date object
How do I calculate the date six months from the current date using the datetime Python module?
Just parse it into a Python datetime object and use its replace() method.
from datetime import datetime
years_ago = 2
date = datetime.strptime('202011','%Y%m')
date = date.replace(year=date.year-years_ago)
# This is the modified date object
print(date)
# Formatted back in your format
print(date.strftime('%Y%m'))
This solution does not require any external dependency
Here's a similar solution to the others, but only using the standard library, and as a function.
def subtract_years(date_string: str, diff: int) -> str:
dt = datetime.strptime(date_string, "%Y%m")
new_dt = dt.replace(year=dt.year - diff)
return new_dt.strftime("%Y%m")
# ❯ subtract_years("202011", 2)
# '201811'
Related
I want to get last three months from todays date in year-mon format. For example if todays date is 2021-08-04 then I want list of last three months as -
["2021-05", "2021-06", "2021-07"]
I have no idea how to start with this. Any help will be appreciated.
use dateutil's relativedelta to get consistent results, as not all months have equal number of days. E.g.
from datetime import datetime
from dateutil.relativedelta import relativedelta
NOW = datetime.now() # reference date
delta = relativedelta(months=-1) # delta in time
n = 3 # how many steps
fmt = lambda dt: dt.strftime("%Y-%m") # formatter; datetime object to string
l = sorted((fmt(NOW+delta*i) for i in range(1, n+1)))
# l
# ['2021-05', '2021-06', '2021-07']
I have the following string format (Python 3.6):
'2018-11-19T10:04:57.426872'
I get it as a parameter to my script.
I want to get the date as 'YYYY-MM-DD' and time as 'HH:MM'
I tried to convert it with:
from datetime import datetime
if __name__ == '__main__':
start_timestamp = sys.argv[1]
start_date = datetime.strptime(sys.argv[1], '%Y-%m-%d')
start_time = datetime.strptime(sys.argv[1], '%H:%M')
But this gives:
ValueError: unconverted data remains: T10:04:57.426872
In the above example I want to see:
start_date = '2018-11-19'
start_time = '10:04'
Since the date seems to be in ISO-Format, a simple
start = datetime.datetime.fromisoformat(text)
will parse it correctly. From there you can get your date and time with
start_date = start.strftime("%Y-%m-%d")
start_time = start.strftime("%H:%M")
Edit:
For Python < 3.7, you can use this format:
start = datetime.datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f")
For the "duplicate" datetime confusion: I used import datetime. If you use from datetime import datetime, you can get rid of the additional datetime.
Try this:We have one of the best package for parsing dates called dateutil.
from dateutil import parser
date1='2018-11-19T10:04:57.426872'
print 'Start_date:',parser.parse(date1).strftime("%Y-%m-%d")
print 'Start_time:',parser.parse(date1).strftime("%H:%M")
Result:Start_date:2018-11-19
Start_time:10:04
You need to parse the entire string into one datetime object and then extract your required values from that.
dt = datetime.datetime.strptime('2018-11-19T10:04:57.426872', '%Y-%m-%dT%H:%M:%S.%f')
d = dt.date()
t = dt.time()
print(d.strftime('%Y-%m-%d'))
print(t.strftime('%H:%M'))
Which outputs:
2018-11-19
10:04
I have the format
day/month/year
And I have a task to define a function that takes a date and returns the date with 1 day increased
Example:
next_day("13/1/2018") returns 14/1/2018
next_day("31/3/2018") returns 1/4/2018
How can I do that, I don't know how to do this when the function takes date not day, month, year.
This is one way using the 3rd party dateutil library and datetime from the standard library.
import datetime
from dateutil import parser
def add_day(x):
try:
new = parser.parse(x) + datetime.timedelta(days=1)
except ValueError:
new = parser.parse(x, dayfirst=True) + datetime.timedelta(days=1)
return new.strftime('%d/%m/%Y').lstrip('0').replace('/0', '/')
add_day('13/1/2018') # '14/1/2018'
add_day('31/3/2018') # '1/4/2018'
Trying to perform the same logic with datetime will be more restrictive, which is probably not what you want since it's not obvious you can guarantee the format of your input dates.
Explanation
Try parsing sequentially with month first (default), then day first.
Add a day using datetime.timedelta.
Use string formatting to remove leading zeros.
Pure datetime solution
import datetime
def add_day(x):
try:
new = datetime.datetime.strptime(x, '%m/%d/%Y') + datetime.timedelta(days=1)
except ValueError:
new = datetime.datetime.strptime(x, '%d/%m/%Y') + datetime.timedelta(days=1)
return new.strftime('%d/%m/%Y').lstrip('0').replace('/0', '/')
add_day('13/1/2018') # '14/1/2018'
add_day('31/3/2018') # '1/4/2018'
You can try this function to return the current date at least.
extension Date {
var withWeekDayMonthDayAndYear: String {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(abbreviation: "EST")
formatter.dateFormat = "EEEE, MMMM dd, yyyy"
return formatter.string(from: self)
}
Then use the extension..
((Date().withWeekDayMonthDayAndYear))
It's a start..
I have a date string formatted like this: "2017-05-31T06:44:13Z".
I need to check whether this date is within a one year span from today's date.
Which is the best method to do it: convert it into a timestamp and check, or convert into a date format?
Convert the timestamp to a datetime object so it can be compared with other datetime objects using <, >, =.
from datetime import datetime
from dateutil.relativedelta import relativedelta
# NOTE this format basically ignores the timezone. This may or may not be what you want
date_to_check = datetime.strptime('2017-05-31T06:44:13Z', '%Y-%m-%dT%H:%M:%SZ')
today = datetime.today()
one_year_from_now = today + relativedelta(years=1)
if today <= date_to_check <= one_year_from_now:
# do whatever
Use the datetime package together with timedelta:
import datetime
then = datetime.datetime.strptime("2017-05-31T06:44:13Z".replace('T',' ')[:-1],'%Y-%m-%d %H:%M:%S')
now = datetime.datetime.now()
d = datetime.timedelta(days = 365)
and simply check if now-d > then.
I'm pulling a timestamp that looks like this - 2014-02-03T19:24:07Z
I'm trying to calculate the number of days since January 1.
I was able to convert it to datetime using
yourdate = dateutil.parser.parse(timestamp)
But now I'm trying to parse it and grab individual elements, such as the month & day.
Is there a way to convert it to strptime so I can select each element?
Just access the month, day using year, month, day attributes..
>>> import dateutil.parser
>>> yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
>>> yourdate.year
2014
>>> yourdate.month
2
>>> yourdate.day
3
Just to be a little more complete:
>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> import pytz
>>> d = parse('2014-02-03T19:24:07Z')
>>> other = datetime(year=2014, month=1, day=1, tzinfo=pytz.utc)
>>> (d-other).days
33
You have to make sure the other datetime is timezone aware if you're creating it with datetime as opposed to the datetime you're parsing with dateutil.
There's no need for converting. The resulting datetime.datetime object has all necessary properties which you can access directly. For example:
>>> import dateutil.parser
>>> timestamp="2014-02-03T19:24:07Z"
>>> yourdate = dateutil.parser.parse(timestamp)
>>> yourdate.day
3
>>> yourdate.month
2
See: https://docs.python.org/2/library/datetime.html#datetime-objects
if you want to calculate:
import dateutil.parser
yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
startdate = dateutil.parser.parse('2014-01-01T00:00:00Z')
print (yourdate - startdate)
Another way to solve without the dateutil module:
import datetime
# start date for comparision
start = datetime.date(2014, 1, 1)
# timestamp as string
datefmt = "%Y-%m-%dT%H:%M:%SZ"
current = "2014-02-03T19:24:07Z"
# convert timestamp string to date, dropping time
end = datetime.datetime.strptime(current, datefmt).date()
# compare dates and get number of days from timedelta object
days = (end - start).days
This assumes you don't care about time (including timezones).