Python Forum
Convert text file date into specific format
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert text file date into specific format
#1
Do anyone know how to convert a text file date format to specific format.
For example i have a text file and the file is 2018/01/02, and i wants to convert in into 20180102.
In hoilday.txt have many date in this format( year/m/d), and i wants to change to ymd format.

import datetime as dt
with open('holiday.txt') as f, open('new.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
	f_out.write(dt.strftime('%d%m%Y'))
	
Reply
#2
If it is a text you do not need datetime module.
Read the dates and replace '/' with "".

>>> line = "2018/01/02"
>>> line.replace('/', '')
'20180102'
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
0K thanks a lots.
i figure it out.
Reply
#4
Just for completeness, let's show transformation using datetime.datetime , because it would be useful for more complicated formats/conversions

from datetime import datetime
d = "2018/01/02"
print(datetime.strftime(datetime.strptime(d, '%Y/%m/%d'), '%Y%m%d'))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Hi this is my code.
It work, but i have another question.
What if my file have date and some word like this
2018/01/02 XXXXX
2018/01/03 cccccc

How can I just changed the date.
If i remove the word it can be success, but if i put the word in it, i will run error.
It will occur "ValueError: unconverted data remains: xxxxx"
Is there a way to fix this.

import datetime as dt
from datetime import datetime
with open('holiday.txt') as f, open('new.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
	#line =line.replace('/', '')
	#f_out.write('{}\n'.format(line))
	f_out.write(datetime.strftime(datetime.strptime(line, '%Y/%m/%d'), '%Y%m%d'))
thanks
Reply
#6
Split the line. Get the first element, convert it to the desired format and put the line back together.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
is there any example i can reference to?
thanks
Reply
#8
>>> line = '2018/01/03 cccccc'
>>> date = line.split()[0].replace('/', '')
>>> date
'20180103'
>>> new_line = f'{date}{line[line.index(" "):]}'
>>> new_line
'20180103 cccccc'
For examaple. Or you can modify it to use datetime. Try with datetime because you are working with dates so you have to practise.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#9
Thanks. I solve it
This is my code. Is there any comment with my code, or any suggestion.

import datetime as dt
from datetime import datetime
with open('holiday.txt') as f, open('new.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
	#line =line.replace('/', '')
	#f_out.write('{}\n'.format(line))
	#f_out.write(datetime.strftime(datetime.strptime(line, '%Y/%m/%d'), '%Y%m%d'))
	line.rstrip().split('  ')
	line_1 = line.split()[0]
	line_2 = line.split()[1]
	newline =(datetime.strftime(datetime.strptime(line_1, '%Y/%m/%d'), '%Y%m%d'))
	#result = line_1 +" " +line_2
	#f_out.write(result)
	f_out.write(line_1 +" " +line_2+ '\n')
Reply
#10
I don't think this would work as expected.
You need lines 9-15 indented one level or you will get just the last line processed.
Also you don't need one of the imports (better keep the second one). There are other lines of code that yield nothing.
Finally you write the date again using line_1, not newline


from datetime import datetime
with open('holiday.txt') as f, open('new.txt', 'w') as f_out:
    for line in f:
        line_1, line_2 = line.rstrip().split('  ')
        new_line_1 =(datetime.strftime(datetime.strptime(line_1, '%Y/%m/%d'), '%Y%m%d'))
        f_out.write('{} {}\n'.format(new_line_1, line_2))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 220 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
Question [SOLVED] Correct way to convert file from cp-1252 to utf-8? Winfried 8 803 Feb-29-2024, 12:30 AM
Last Post: Winfried
  Extracting specific file from an archive tester_V 4 502 Jan-29-2024, 06:41 PM
Last Post: tester_V
  Python date format changes to date & time 1418 4 589 Jan-20-2024, 04:45 AM
Last Post: 1418
Thumbs Up Convert word into pdf and copy table to outlook body in a prescribed format email2kmahe 1 746 Sep-22-2023, 02:33 PM
Last Post: carecavoador
  Color a table cell based on specific text Creepy 11 1,963 Jul-27-2023, 02:48 PM
Last Post: deanhystad
  Convert File to Data URL michaelnicol 3 1,151 Jul-08-2023, 11:35 AM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 1,253 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  Python Script to convert Json to CSV file chvsnarayana 8 2,499 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Review my code: convert a HTTP date header to a datetime object stevendaprano 1 1,986 Dec-17-2022, 12:24 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020