I am trying to print the date and month as 2 digit numbers.
timestamp = date.today()
difference = timestamp - datetime.timedelta(localkeydays)
localexpiry = '%s%s%s' % (difference.year, difference.month, difference.day)
print localexpiry
This gives the output as 201387. This there anyway to get the output as 20130807. This is because I am comparing this against a string of a similar format.
Use date formatting with date.strftime():
difference.strftime('%Y%m%d')
Demo:
>>> from datetime import date
>>> difference = date.today()
>>> difference.strftime('%Y%m%d')
'20130807'
You can do the same with the separate integer components of the date object, but you need to use the right string formatting parameters; to format an integer to two digits with leading zeros, use %02d, for example:
localexpiry = '%04d%02d%02d' % (difference.year, difference.month, difference.day)
but using date.strftime() is more efficient.
You can also use format (datetime, date have __format__ method):
>>> import datetime
>>> dt = datetime.date.today()
>>> '{:%Y%m%d}'.format(dt)
'20130807'
>>> format(dt, '%Y%m%d')
'20130807'
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