Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Modifying a date format
#11
(Oct-28-2022, 08:58 AM)Larz60+ Wrote: You don't need testit.
try this (as I cannot test):

Thanks, I only had to modify line 5 as it didn't like double quotes within the "F" statement, so ..

import datetime

def convert_date(orig):
    massaged_date = orig.replace("'", "/")[1:]
    return f"D{datetime.datetime.strftime(datetime.datetime.strptime(massaged_date, '%m/%d/%Y'), '%m/%d/%Y')}"

def clean_file(filename):
    with open(filename,"r") as f:
        line = f.readline().strip()

        if line[0] == "D":      # this could also read "if line.startswith("D"):"
            convert_date(line)
            print(line)
        else:
            print(line)

clean_file("ANCU.qif")
it only read one line, so I added a "for" loop but that didn't work.
Reply
#12
(Oct-28-2022, 10:23 AM)rob101 Wrote: As I had 10 mins spare, I've come up with a possible solution:

Thanks, I added a loop to read the file, code now ..

def format_date(date):
    for index, item in enumerate(date):
        if index == 0:
            month = item.lstrip("D")
            month = "D" + str(f"{int(month):02d}")
        elif index == 1:
            day = str(f"{int(item):02d}")
        else:
            year = item.rstrip("\n")

    return f"{month}/{day}/{year}"

f = open("ANCU.qif","r")
lines = f.readlines()

for line in lines:
    if line[0] == 'D':
        date = format_date(line)
    continue

print(date)

# closing the file
f.close()
Output:
Traceback (most recent call last): File "......search_replace_5.py", line 18, in <module> date = format_date(line) File ".....search_replace_5.py", line 5, in format_date month = "D" + str(f"{int(month):02d}") ValueError: invalid literal for int() with base 10: ''
Reply
#13
(Oct-28-2022, 10:34 PM)jehoshua Wrote: Thanks, I added a loop to read the file, code now ..

Again, you're welcome.

If nothing else in this thread is working for you and you'd like to implement my solution, then I'll need some more information: limited information will produce limited results.

As yet, the only information I have about what is being returned by lines = f.readlines() is what you've posted: a list object such as ['D6', '30', '2005\n'] or ['D7', '7', '2005\n']. I'm guessing that the list object contains more than that.
jehoshua likes this post
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#14
(Oct-28-2022, 12:53 PM)DeaD_EyE Wrote:
import datetime

input_format = "D%d/%m'%Y"
output_format = "%d/%m/%Y"

datetime.datetime.strptime("D4/7'2004", input_format).strftime(output_format)

Thank you. I added a bit of code to read the file as follows ..

import datetime

input_format = "D%d/%m'%Y"
output_format = "%d/%m/%Y"

f = open("ANCU.qif","r")
lines = f.readlines()

for line in lines:

    if line[0] == "D":
        new_date = datetime.datetime.strptime(line.strip(), input_format).strftime(output_format)
        print(new_date)
    else:
        line = line.strip()
        print(line)

# closing the file
f.close()
and it worked for 34 records, then ..

Output:
Traceback (most recent call last): File "....search_replace_6.py", line 12, in <module> new_date = datetime.datetime.strptime(line.strip(), input_format).strftime(output_format) File "/usr/lib/python3.10/_strptime.py", line 568, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) File "/usr/lib/python3.10/_strptime.py", line 349, in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data "D3/29'2004" does not match format "D%d/%m'%Y"
of course line 12 is the line I modified. However, the previous date records were okay because they were all

D3/11'2004

and this date record was

D3/29'2004

so the code thought the month was 29
Reply
#15
(Oct-28-2022, 10:59 PM)rob101 Wrote: I'm guessing that the list object contains more than that.

Yes, I'll create some test data. Thanks
Reply
#16
(Oct-28-2022, 11:20 PM)jehoshua Wrote: so the code thought the month was 29

The input_format was wrong.
input_format = "D%d/%m'%Y"
-> day/month/year

But it seems to be month/day/year
This should work
input_format = "D%m/%d'%Y"
More info about the shortcuts: https://docs.python.org/3/library/dateti...rmat-codes
jehoshua likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#17
(Oct-29-2022, 03:10 PM)DeaD_EyE Wrote: This should work

Thanks, yes it works fine now as:

import datetime

input_format = "D%m/%d'%Y"
output_format = "D%m/%d/%Y"

f = open("ANCU.qif","r")
lines = f.readlines()

for line in lines:

    if line[0] == "D":
        new_date = datetime.datetime.strptime(line.strip(), input_format).strftime(output_format)
        print(new_date)
    else:
        line = line.strip()
        print(line)

# closing the file
f.close()
Reply
#18
(Oct-28-2022, 11:23 PM)jehoshua Wrote: Yes, I'll create some test data. Thanks

Some test data at https://pastebin.com/raw/FnueXARj
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 267 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  Python date format changes to date & time 1418 4 635 Jan-20-2024, 04:45 AM
Last Post: 1418
  Date format error getting weekday value Aggie64 2 1,431 May-29-2022, 07:04 PM
Last Post: Aggie64
  Convert Date to another format lonesoac0 2 1,684 Mar-17-2022, 11:26 AM
Last Post: DeaD_EyE
  Format SAS DATE Racer_x 0 1,005 Feb-09-2022, 04:44 PM
Last Post: Racer_x
  How can I compare 2 format of date? korenron 4 1,546 Dec-21-2021, 12:40 PM
Last Post: korenron
  Modifying code cheburashka 1 1,319 Dec-13-2021, 01:01 PM
Last Post: Kebap
  Date format and past date check function Turtle 5 4,314 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  Print first day of the week as string in date format MyerzzD 2 2,044 Sep-29-2021, 06:43 AM
Last Post: MyerzzD
  String to Date format SAF 2 2,479 Apr-06-2021, 02:09 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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