In my table, I have different types of dates just with numbers and in this two formats:
yyyy-m-d
yyyy-mm-dd
Some values, as the month for example, don't have the zero in the case of months under 10 and I need it to create a condition to chose elements by the latest date.
I want that all of them have the same format:
yyyy-mm-dd
Any pythonic way to solve that?
For the moment I am using this:
if line.startswith('# Date: '):
#date = 2014-5-28
d = line.strip().split(':')[-1].split('-').replace(' ','')
if len(d[0]) == 4:
year = str(d[0])
elif len(d[1]) < 2:
month = '0'+ str(d[1])
elif len(d[2]< 2):
day = '0'+ str(d[1])
date = year + month + day
yyyy-mm-dd stands for year-month-day . We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime.
Use strftime() function of a datetime class For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
You can use the python inbuilt datetime module
import datetime
date1 = "2018-1-1"
date2 = "2018-01-01"
datetime_object = datetime.datetime.strptime(date1, "%Y-%m-%d")
datetime_object2 = datetime.datetime.strptime(date2, "%Y-%m-%d")
print datetime_object.strftime("%Y-%m-%d")
print datetime_object2.strftime("%Y-%m-%d")
Result:
2018-01-01
2018-01-01
Try the below code ! You have to import the date time file .
Input :
import datetime
date1 = datetime.datetime.strptime("2015-1-3", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)
today = datetime.date.today().strftime("%d-%m-%Y")
print(today)
Output :
03-01-2015
17-01-2018
You can try:
>>> d = "2018-1-1"
>>> d_list = d.split("-")
>>> d_list
['2018', '1', '1']
>>> if len(d_list[1]) < 2:
d_list[1] = "0"+d_list[1]
>>> if len(d_list[2]) < 2:
d_list[2] = "0"+d_list[2]
>>> d_list
['2018', '01', '01']
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