Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date format yyyy-m-d into yyyy-mm-dd on Python

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 
like image 906
F.Lira Avatar asked Jan 17 '18 10:01

F.Lira


People also ask

How do I change date format from YYYY to MM DD in Python?

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.

How do you change date format from Yyyymmdd to mm/dd/yyyy in Python?

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.


3 Answers

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
like image 172
Rakesh Avatar answered Oct 01 '22 08:10

Rakesh


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
like image 20
Usman Avatar answered Oct 01 '22 08:10

Usman


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']
like image 39
Harsha Biyani Avatar answered Oct 01 '22 08:10

Harsha Biyani