Python Forum
Update Date based on Time/String - 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: Update Date based on Time/String (/thread-31898.html)



Update Date based on Time/String - stevezemlicka - Jan-08-2021

I am absolutely new to Python. While having a bit of experience with perl, ruby, and some other programming languages, I figure it's about time I delve into and learn Python.

Most of my successes in learning tech is to solve an actual problem with it and build on that. So my problem as it sits now is I have a data set. Part of this data is time/date stamps. A sample of the data is below:

Quote:15,07/31/2020 1600,1048,31,0
15,07/31/2020 1700,1086,45,0
15,07/31/2020 1800,1092,42,0
15,07/31/2020 1900,1017,20,1
15,07/31/2020 2000,945,0,28
15,07/31/2020 2100,897,0,43
15,07/31/2020 2200,869,0,55
15,07/31/2020 2300,812,0,72
15,07/31/2020 0000,778,0,82

I need to detect every occurrence of 0000 in the second column (though I don't believe there are any other occurrences of 0000 in any other column so column isolation is probably not necessary) and increase the date by +1 day. So, in the above example, the expected result would be:

Quote:15,07/31/2020 1600,1048,31,0
15,07/31/2020 1700,1086,45,0
15,07/31/2020 1800,1092,42,0
15,07/31/2020 1900,1017,20,1
15,07/31/2020 2000,945,0,28
15,07/31/2020 2100,897,0,43
15,07/31/2020 2200,869,0,55
15,07/31/2020 2300,812,0,72
15,08/01/2020 0000,778,0,82

I suppose I could do this with a combination of awk or perl scripts or maybe even just perl but I think this would be a great way to get my feet wet with Python. Can someone give me some guidance on what is needed to use Python to make this modification?


RE: Update Date based on Time/String - Gribouillis - Jan-08-2021

There are probably several ways to do this in python. You could simply open the file and process each line, then write it to stdout. Here is one way to process a single line
>>> import datetime as dt
>>> day = dt.timedelta(days=1)
>>> 
>>> s = "15,08/01/2020 0000,778,0,82"
>>> e = s.split(',', 2)
>>> e
['15', '08/01/2020 0000', '778,0,82']
>>> if e[1].endswith('0000'):
...     d = dt.datetime.strptime(e[1].split()[0], '%d/%M/%Y')
...     e[1] = '{:%d/%M/%Y} 0000'.format(d + day)
...     s = ','.join(e)
... 
>>> s
'15,09/01/2020 0000,778,0,82'