Parse date string and change format
Asked Answered
H

10

226

I have a date string with the format 'Mon Feb 15 2010'. I want to change the format to '15/02/2010'. How can I do this?

Hunkers answered 15/2, 2010 at 10:49 Comment(3)
Duplicate of all of these: stackoverflow.com/search?q=%5Bpython%5D+parse+date. Exact duplicate of thise: #1714094Medium
Does this answer your question? Converting string into datetimeEloyelreath
Does this answer your question? Parse a string with a date to a datetime objectAvertin
O
283

The datetime module could help you with that:

datetime.datetime.strptime(input_date_string, input_format).strftime(output_format)

For the specific example, you could do:

>>> from datetime import datetime
>>> datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'

Learn more about different formats here.

Ossie answered 15/2, 2010 at 10:54 Comment(3)
format1 needs to be a string to express the input date string's format. format2 is the target string format to output.Stephi
Tutorial for strptime and its format string: tutorialspoint.com/python/time_strptime.htmDisjunct
strptime and strftime are really powerful functions. It's weird I couldn't find them in the python docsLermontov
O
115

You can install the dateutil library. Its parse function can figure out what format a string is in without having to specify the format like you do with datetime.strptime.

from dateutil.parser import parse
dt = parse('Mon Feb 15 2010')
print(dt)
# datetime.datetime(2010, 2, 15, 0, 0)
print(dt.strftime('%d/%m/%Y'))
# 15/02/2010
Obannon answered 20/4, 2013 at 1:25 Comment(4)
dateutil.parse is a better alternative if the exact format of a legal ISO string is unknown. ISO may or may not contain microseconds. It may or may not contain trailing "Z". datetime.strptime is not flexible enough to accomodate for that.Caroncarotene
Pase Date should be used with care. parse('12.07.2017') returns datetime(2017, 12, 7, ..) but parse('13.07.2017') returns .datetime(2017, 7, 13, ...)Reborn
In python 3.x needs to install python-dateutil pip install python-dateutilOath
Just an update from Michael Kariv, parse provides a param dayfirst that will be used to deferentiate between YDM and YMD dates parse docs.)Killigrew
B
38

Convert a string to a datetime object:

from datetime import datetime
s = "2016-03-26T09:25:55.000Z"
f = "%Y-%m-%dT%H:%M:%S.%fZ"
out = datetime.strptime(s, f)
print(out)

Output:

2016-03-26 09:25:55
Benefield answered 26/3, 2016 at 13:54 Comment(2)
This is not according to the format he asked, which had a month string "Feb" in it.Delastre
@ShahirAnsari you can change the format as you like refer "docs.python.org/3/library/datetime.html"Benefield
B
27
>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'
Baronetage answered 15/2, 2010 at 11:16 Comment(0)
A
17

As this question comes often, here is the simple explanation.

datetime or time module has two important functions.

  • strftime - creates a string representation of date or time from a datetime or time object.
  • strptime - creates a datetime or time object from a string.

In both cases, we need a formating string. It is the representation that tells how the date or time is formatted in your string.

Now lets assume we have a date object.

>>> from datetime import datetime
>>> d = datetime(2010, 2, 15)
>>> d
datetime.datetime(2010, 2, 15, 0, 0)

If we want to create a string from this date in the format 'Mon Feb 15 2010'

>>> s = d.strftime('%a %b %d %y')
>>> print s
Mon Feb 15 10

Lets assume we want to convert this s again to a datetime object.

>>> new_date = datetime.strptime(s, '%a %b %d %y')
>>> print new_date
2010-02-15 00:00:00

Refer This document all formatting directives regarding datetime.

Annmarieannnora answered 3/10, 2016 at 9:51 Comment(0)
M
4

@codeling and @user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.

import datetime

x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)

Output:

15/02/2010
Molybdenum answered 6/6, 2018 at 20:28 Comment(0)
M
3

You may achieve this using pandas as well:

import pandas as pd

pd.to_datetime('Mon Feb 15 2010', format='%a %b %d %Y').strftime('%d/%m/%Y')

Output:

'15/02/2010'

You may apply pandas approach for different datatypes as:

import pandas as pd
import numpy as np

def reformat_date(date_string, old_format, new_format):
    return pd.to_datetime(date_string, format=old_format, errors='ignore').strftime(new_format)

date_string = 'Mon Feb 15 2010'
date_list = ['Mon Feb 15 2010', 'Wed Feb 17 2010']
date_array = np.array(date_list)
date_series = pd.Series(date_list)

old_format = '%a %b %d %Y'
new_format = '%d/%m/%Y'

print(reformat_date(date_string, old_format, new_format))
print(reformat_date(date_list, old_format, new_format).values)
print(reformat_date(date_array, old_format, new_format).values)
print(date_series.apply(lambda x: reformat_date(x, old_format, new_format)).values)

Output:

15/02/2010
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
['15/02/2010' '17/02/2010']
Mylonite answered 26/12, 2019 at 10:25 Comment(0)
H
2

Just for the sake of completion: when parsing a date using strptime() and the date contains the name of a day, month, etc, be aware that you have to account for the locale.

It's mentioned as a footnote in the docs as well.

As an example:

import locale
print(locale.getlocale())

>> ('nl_BE', 'ISO8859-1')

from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'

locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> '2016-03-06'
Haematoblast answered 28/7, 2016 at 18:59 Comment(0)
I
1

Use the strptime() and strftime() functions in the datetime library.

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

Examples: 3. Dates and Times

Incomprehensive answered 15/2, 2010 at 11:11 Comment(1)
for the error above nimmyliji you should have done datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y") it gives '15/02/2010'Incomprehensive
D
1

If you dont want to define the input date format then, Install dateparser (pip install dateparser) and,

from dateparser import parse
parse("Mon Feb 15 2010").strftime("%d/%m/%Y")
Drawn answered 22/12, 2022 at 13:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.