5

I'm trying to parse a date and put it in the correct format, this is what I tried so far:

import csv
import sys
import os
import re
import fnmatch
import csv
from dateutil.parser import parse as parseDate
from datetime import datetime, time, timedelta

chaine = '16/12/201602:15:00'
date = chaine[:10] + " " + chaine[11:]
print date
newd = parseDate(date, yearfirst=True)
print newd
newd = newd.replace('-','')
newd = newd.replace(':','')
print newd

This is what I get as result:

16/12/2016 2:15:00
2016-12-16 02:15:00
Traceback (most recent call last):
  File "t.py", line 25, in <module>
    newd = newd.replace('-','')
TypeError: an integer is required

What do I miss here?

Thank you

4
  • 3
    newd is not a string. Try using newd = str(newd).replace('-','') instead of newd = newd.replace('-',''). Commented Jan 4, 2017 at 8:50
  • 1
    thank you! could you put an answer so that i can accept it :) Commented Jan 4, 2017 at 8:54
  • 1
    if your date is '16/12/201602:15:00', then your setting for yearfirst in parseDate(date, yearfirst=True) seems to be wrong too, but without effect on the result, so you can drop that option Commented Jan 4, 2017 at 9:12
  • 1
    That's right! THank you @MaartenFabré Commented Jan 4, 2017 at 9:15

2 Answers 2

8

To fix your current logic, you need to cast the newd variable to a string after parseDate:

newd = str(newd).replace('-','')
       ^^^^^^^^^ 

See the Python demo

Alternatively, use the strptime / strftime:

from dateutil.parser import parse as parseDate
from datetime import datetime, time, timedelta
from time import strftime

chaine = '16/12/201602:15:00'
dt = datetime.strptime(chaine, '%d/%m/%Y%I:%M:%S')
# 16/12/2016 2:15:00
print(dt.strftime("%Y/%m/%d %H:%M:%S"))
#2016-12-16 02:15:00
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
# 20161216 021500
print(dt.strftime("%Y%m%d %H%M%S"))

See another Python demo.

Sign up to request clarification or add additional context in comments.

2 Comments

better would be to use strftime
@MaartenFabré: Yes, I know, just did not have time to prepare a demo. Added now.
0

In your code newd is a datetime.datetime object, not a string. you can see it with

print type(newd)  shows <type 'datetime.datetime'>   

so you cannot use a string replacement.
you can use discrete properties like

 newd.year .month .day etc. 

to create your own string.( more on Python doc )
or play more quickly with the strftime method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.