0

In python is there a better way to convert from a US date format to a UK date format?

I am using the below:

df = ['01/31/2014', '02/06/2013']

for a in df:
    s = list(a)
    d = [s[3],s[4],s[2],s[0],s[1],s[5],s[6],s[7],s[8],s[9]]
    f.append("".join(d))

print (f)

['31/01/2014', '06/02/2013']
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
beng986
  • 71
  • 1
  • 1
  • 8

3 Answers3

5

Use this instead,

datetime.datetime.strptime(your_date, '%m/%d/%Y').strftime('%d/%m/%Y')
Ammar Aslam
  • 560
  • 2
  • 16
Dharmik
  • 445
  • 3
  • 10
2

Here is a one liner:

from datetime import datetime

df = ['01/31/2014', '02/06/2013']    
f = [datetime.strptime(d, "%m/%d/%Y").strftime("%d/%m/%Y") for d in df]
print(f)

prints

['31/01/2014', '06/02/2013']
Selcuk
  • 57,004
  • 12
  • 102
  • 110
1

Turn it into a date with datetime.datetime.strptime, then use date.strftime to turn it back into a string.

Always attempt to work with dates as dates, not as strings. Ideally turning them into dates as early as you can and not going back to strings until you absolutely have to.

Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81