I am creating a module in python, in which I am receiving the date in integer format like 20120213, which signifies the 13th of Feb, 2012. Now, I want to convert this integer formatted date into a python date object.
Also, if there is any means by which I can subtract/add the number of days in such integer formatted date to receive the date value in same format? like subtracting 30 days from 20120213 and receive answer as 20120114?
You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp.
I would suggest the following simple approach for conversion:
from datetime import datetime, timedelta s = "20120213" # you could also import date instead of datetime and use that. date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))   For adding/subtracting an arbitary amount of days (seconds work too btw.), you could do the following:
date += timedelta(days=10) date -= timedelta(days=5)   And convert back using:
s = date.strftime("%Y%m%d")   To convert the integer to a string safely, use:
s = "{0:-08d}".format(i)   This ensures that your string is eight charecters long and left-padded with zeroes, even if the year is smaller than 1000 (negative years could become funny though).
Further reference: datetime objects, timedelta objects
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With