Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert integer into date object python?

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?

like image 834
Uday0119 Avatar asked Mar 17 '12 13:03

Uday0119


People also ask

How do you convert an integer to a date object in Python?

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.


1 Answers

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

like image 163
Jonas Schäfer Avatar answered Sep 19 '22 11:09

Jonas Schäfer