Convert to dd mm yyyy in python

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.

This almost works, but fails because I don't provide time:

from datetime import datetime

lastconnection = datetime.strptime["21/12/2008", "%Y-%m-%d"]

#ValueError: time data did not match format:  data=21/12/2008  fmt=%Y-%m-%d
print lastconnection

I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.

asked Feb 2, 2009 at 10:01

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime["21/12/2008", "%d/%m/%Y"].strftime["%Y-%m-%d"]

The call to strptime[] parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime[] to format the result into the desired final format.

Hans Z.

47.5k11 gold badges96 silver badges111 bronze badges

answered Feb 2, 2009 at 10:09

unwindunwind

383k64 gold badges462 silver badges594 bronze badges

1

you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:

lastconnection = datetime.strptime["21/12/2008", "%d/%m/%Y"].strftime['%Y-%m-%d']

answered Feb 2, 2009 at 10:07

SilentGhostSilentGhost

293k64 gold badges301 silver badges291 bronze badges

1

I am new to programming. I wanted to convert from yyyy-mm-dd to dd/mm/yyyy to print out a date in the format that people in my part of the world use and recognise.

The accepted answer above got me on the right track.

The answer I ended up with to my problem is:

import datetime

today_date = datetime.date.today[]
print[today_date]

new_today_date = today_date.strftime["%d/%m/%Y"]
print [new_today_date]

The first two lines after the import statement gives today's date in the USA format [2017-01-26]. The last two lines convert this to the format recognised in the UK and other countries [26/01/2017].

You can shorten this code, but I left it as is because it is helpful to me as a beginner. I hope this helps other beginner programmers starting out!

SiHa

7,12212 gold badges32 silver badges42 bronze badges

answered Jan 26, 2017 at 12:37

MarkMark

3754 silver badges10 bronze badges

2

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'

This will almost certainly be faster than the conversion to and from a date.

answered Feb 2, 2009 at 10:53

paxdiablopaxdiablo

826k227 gold badges1547 silver badges1915 bronze badges

2

#case_date= 03/31/2020   

#Above is the value stored in case_date in format[mm/dd/yyyy ]

demo=case_date.split["/"]
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is [dd/mm/yyyy] test by printing it 
print[new_case_date]

answered Apr 10, 2020 at 13:19

If you need to convert an entire column [from pandas DataFrame], first convert it [pandas Series] to the datetime format using to_datetime and then use .dt.strftime:

def conv_dates_series[df, col, old_date_format, new_date_format]:

    df[col] = pd.to_datetime[df[col], format=old_date_format].dt.strftime[new_date_format]
    
    return df

Sample usage:
import pandas as pd

test_df = pd.DataFrame[{"Dates": ["1900-01-01", "1999-12-31"]}]

old_date_format='%Y-%m-%d'
new_date_format='%d/%m/%Y'

conv_dates_series[test_df, "Dates", old_date_format, new_date_format]

    Dates
0   01/01/1900
1   31/12/1999

answered Apr 5, 2020 at 19:10

mirekphdmirekphd

3,26025 silver badges44 bronze badges

The most simplest way

While reading the csv file, put an argument parse_dates

df = pd.read_csv["sample.csv", parse_dates=['column_name']]

This will convert the dates of mentioned column to YYYY-MM-DD format

Josef

2,3401 gold badge20 silver badges22 bronze badges

answered May 9, 2021 at 8:16

Convert date format DD/MM/YYYY to YYYY-MM-DD according to your question, you can use this:

from datetime import datetime
lastconnection = datetime.strptime["21/12/2008", "%d/%m/%Y"].strftime["%Y-%m-%d"]
print[lastconnection]

answered Nov 2, 2021 at 9:42

RokiDGuptaRokiDGupta

3211 gold badge6 silver badges13 bronze badges

  • df is your data frame
  • Dateclm is the column that you want to change

This column should be in DateTime datatype.

df['Dateclm'] = pd.to_datetime[df['Dateclm']]

df.dtypes


#Here is the solution to change the format of the column

df["Dateclm"] = pd.to_datetime[df["Dateclm"]].dt.strftime['%Y-%m-%d']

print[df]

Peter Csala

12.2k15 gold badges24 silver badges55 bronze badges

answered Dec 30, 2021 at 8:33

1

How do I convert date to mm/dd/yyyy in Python?

Use datetime. strftime[format] to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.

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

Python Regular Expression: Exercise-25 with Solution.
Sample Solution:-.
Python Code: import re def change_date_format[dt]: return re.sub[r'[\d{4}]-[\d{1,2}]-[\d{1,2}]', '\\3-\\2-\\1', dt] dt1 = "2026-01-02" print["Original date in YYY-MM-DD Format: ",dt1] print["New date in DD-MM-YYYY Format: ",change_date_format[dt1]].

How do I change date format in Python?

from datetime import datetime..
date_time_str = '18/09/19 01:55:19'.
date_time_obj = datetime. strptime[date_time_str, '%d/%m/%y %H:%M:%S'].
print ["The type of the date is now", type[date_time_obj]].

How do I check if a date is in mm/dd/yyyy in Python?

How to validate a date string format in Python.
date_string = '12-25-2018'.
format = "%Y-%m-d".
datetime. datetime. strptime[date_string, format].
print["This is the correct date string format."].
except ValueError:.
print["This is the incorrect date string format. It should be YYYY-MM-DD"].

Chủ Đề