Date Format Changing Program Not Working - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Date Format Changing Program Not Working (/thread-1837.html) |
Date Format Changing Program Not Working - pyth0nus3r - Jan-28-2017 So below is the program that I am using to change files with European (DD-MM-YYYY) style date to American (MM-DD-YYYY) Style Date: Quote:#! python3 However, the files whose days that have 20-29 in their dates does not work properly. For example, ab12-10-2010test.txt works but ab22-10-2010test.txt does not work. Is there some problem with the regular expression. RE: Date Format Changing Program Not Working - metulburr - Jan-28-2017 Quote:So below is the program that I am using to change files with European (DD-MM-YYYY) style date to American (MM-DD-YYYY) you could just use datetime to convert the date. from datetime import datetime time = '13-01-2017' def convert(t): date_format = "%d-%m-%Y" convert_to_format = "%m-%d-%Y" return datetime.strptime(t, date_format).date().strftime(convert_to_format) print(convert(time))
Quote:For example, ab12-10-2010test.txt works but ab22-10-2010test.txt does not work.then just extract the date portion of the string, convert it, then reinsert the old portion wrapped around the new date format and rename it. The input could be anything even 2-1-2017 and it will still output 01-02-2017
RE: Date Format Changing Program Not Working - Ofnuts - Jan-28-2017 (Jan-28-2017, 05:25 PM)pyth0nus3r Wrote: So below is the program that I am using to change files with European (DD-MM-YYYY) style date to American (MM-DD-YYYY) Style Date: Not very clear... changing European to American or vice-versa? Your regexp implies that your input is American (month first). Several remarks:
datePattern = re.compile(r'([01]?\d)-([0-3]?\d)-((19|20)\d\d)') nameOut=re.sub(datePattern,r'\2-\1-\3',nameIn)If nameOut==nameIn , the regexp was unmatched... or you where dealing with a file dated Jan 1st, Feb 2nd, etc... In any case you don't need to rename the file.
|