datetime(2015,12,1).strftime("%Y/%m/%d")
will do the trick for you. A complete python program would look like this.
# import the datetime and date classes from the datetime module
from datetime import datetime, date
# create your datetime(..) instance from your JSON somehow
# The included Python JSON tools do not usually know about date-times,
# so this may require a special step
# Assume you have a datetime now
dt = datetime(2015,12,1)
# Print it out in your format
print( dt.strftime("%Y/%m/%d") )
Two important details:
- You are using just a date in a Python datetime. Nothing wrong with that but just note that the Python datetime module also has a
date
class
- You can enable your JSON encoder/decoder to recognise dates and datetimes automatically but it requires extra work.
Now, to subtract datetimes from each other they should remain as instances of the datetime
class. You can not subtract datetimes from each other once they have been formatted as a string.
Once you subtract a Python datetime
from an other datetime
the result will be an instance of the timedelta
class.
from datetime import datetime, timedelta
# time_diff here is a timedelta type
time_diff = datetime(2015,12,1) - datetime(2014,11,1)
Now you can look up the Python timedelta type and extract the days, hours, minutes etc. that you need. Be aware that timedeltas can be a negative if you subtract a later datetime from an earlier one.