Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-Digit dates in Python

Tags:

python

date

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.

like image 320
rahuL Avatar asked Apr 12 '26 12:04

rahuL


2 Answers

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.

like image 176
Martijn Pieters Avatar answered Apr 15 '26 00:04

Martijn Pieters


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'
like image 41
falsetru Avatar answered Apr 15 '26 01:04

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!