0

First off, I am very new to all of python. I am now trying to figure out how to replace a time string in a certain column (csv) when that time is greater than the current time.

The script I am building from is relying on petl, so that is what i am using. First, the source csv is opened with petl as table1. It contains multiple columns, one of which is " End time". In this column I would like to replace that time with @time? (for HTML formatting later), only if it is greater than the current time.

the time has the format like "12:15". However, I do not see any change when running the line with >, yet with < all values in the column change.

The line I am struggling with:

current=time.localtime()
table2= petl.convert(table1, ' End time', lambda v, row: '@'+v+'?' if time.strptime(v, '%H:%M') > current else v, pass_row=True)

I would also like to know how I can print or see what time.strptime is using as values, is this possible?

Any ideas are highly appreciated!

flonuts
  • 3
  • 2

1 Answers1

0

If you only pass hour and minute to time.strptime, strptime automatically fills in the missing values for year, month, day with 1900, 1, 1 - so of course that's always less than time.localtime().

If your table contains times in 24 hour format, you can directly compare the time strings from your table with the localtime in the narrower sense (just the TIME part).

To achieve this, use time formatting like so:

current = time.strftime('%H:%M',time.localtime())

It is often helpful to start a python interpreter in a shell and play with the intermediate steps of your computations. Just type the variable, and you will see what it evaluates to:

>>> t2 = time.strptime('12:15', '%H:%M')
>>> t2
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=12, tm_min=15, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
Christoph P
  • 133
  • 6
  • Great, thanks for replying! I see what you mean, if i replace the current variable with strftime it indead outputs a string containing only H and M. However, when comparing it with the time.strptime (1900 etc.) it gives now the reverse effect, (> is always true, < is always false)... – flonuts Apr 28 '20 at 11:28
  • Exactly. If you are new to Python, it will help to learn about introspection, which means that you can always learn about type, attributes and methods of an object, and more. For an introduction, you might start here: http://zetcode.com/lang/python/introspection/ – Christoph P Apr 28 '20 at 11:41
  • Thanks for the info! just to inform, I was unaware strftime could be compared to time in string format, it works great now. Thanks again! – flonuts Apr 28 '20 at 15:20