Monday, 17 February 2020

How can I produce a human readable difference when subtracting two UNIX timestamps using Python?

You can use the wonderful dateutil module and its relativedelta class:
import datetime
import dateutil.relativedelta

dt1 = datetime.datetime.fromtimestamp(123456789) # 1973-11-29 22:33:09
dt2 = datetime.datetime.fromtimestamp(234567890) # 1977-06-07 23:44:50
rd = dateutil.relativedelta.relativedelta (dt2, dt1)

print "%d years, %d months, %d days, %d hours, %d minutes and %d seconds" % (rd.years, rd.months, rd.days, rd.hours, rd.minutes, rd.seconds)
# 3 years, 6 months, 9 days, 1 hours, 11 minutes and 41 seconds
It doesn't count weeks, but that shouldn't be too hard to add.

from : https://stackoverflow.com/questions/6574329/how-can-i-produce-a-human-readable-difference-when-subtracting-two-unix-timestam

How to sort a dataFrame in python pandas by two or more columns?

As of the 0.17.0 release, the sort method was deprecated in favor of sort_valuessort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:
df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:
df.sort(['a', 'b'], ascending=[True, False])

from : https://stackoverflow.com/questions/17141558/how-to-sort-a-dataframe-in-python-pandas-by-two-or-more-columns

Python dictionary increment

An alternative is:
my_dict[key] = my_dict.get(key, 0) + num

from : https://stackoverflow.com/questions/12992165/python-dictionary-increment

Create a column using for loop in Pandas Dataframe

# importing pandas
import pandas as pd
  
# Creating new dataframe
initial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 
                'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 
                'Marks': [12, 52, 36, 85, 23] }
  
df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Marks'])
  
# Generate result using pandas
result = []
for value in df["Marks"]:
    if value >= 33:
        result.append("Pass")
    elif value < 0 and value > 100:
        result.append("Invalid")
    else:
        result.append("Fail")
       
df["Result"] = result   
print(df)

from : https://www.geeksforgeeks.org/create-a-column-using-for-loop-in-pandas-dataframe/