Tag Archives: Python Library Tips

Python Library Tips: timedelta


Timedelta

Timedelta class represent not any particular date or time, but it represents a span of time. This class will be helpful when you need to run some math on date and time. Say what will be this day on after few weeks or what will be this day in future year.

Following example will make it clear

from datetime import date
from datetime import timedelta

print(f'todays date {date.today()} after 1 year will be {date.today()+ timedelta(days=365)}')

Output 
todays date 2020-06-27 after 1 year will be 2021-06-27

Here I used the f.string to construct the message , the timedelta represent one year, 365 days. You can find what will be the date before few weeks back using date -timedelta(weeks=4)

Python Library Tips: strip off letter from list


f.strings

In this series of posts , learn how to use Python Library functions

How to strip off no of letters from a list of strings

The split function of string class can be used to split words from a string. do you know how to creating a abbreviated set of strings from a list. I

With a comprehension statement in Python this can’t be hard

list=['PYTHON','CPYTHON','IPYTHON']
stripped=[ k[:3] for k in list]
print(stripped)
['PYT', 'CPY', 'IPY']

Here we strip of the each list element using : operator in the list and specify the number of characters want to keep.

You can also have the reverse order using k[3:] or can use the starting and ending position as follows

stripped=[ k[0:4] for k in list]
print(stripped)
#['PYTH', 'CPYT', 'IPYT']

stripped=[ k[1:4] for k in list]
print(stripped)
#['YTH', 'PYT', 'PYT']

Python Library Tips: f.strings


f.strings

In Python you can format string in a variety of ways.We learned how to use a %format technique in last post. In Python version 3.7 introduced f.string .

f/F strings are literals begins with letter f/F and It uses { }, curly braces for replacement of expressions with their values

spyder_version=3
python_version=2.7
print(f'I am using Spyder ID {spyder_version} with Python {python_version}')

#Output
I am using Spyder ID 3 with Python 2.7

Arbitrary expression

F"{10*10}"

#Output
100

Function call

We can also call function inside f.strings.

def multi(x,n):
    return x*n
f'{multi(2,2)}'

Multipleline

f-strings are faster than % formatting because they ares constants while f.string expressions are evaluated at runtime.

Also it is possible compose f.strings in multiple line. All strings must begin with ‘f/F’.

>>topic='panda frames'
>>lang='python'
>>version =3.8
>>say=(f'I want to use {topic}'
  f' in {lang}'
  f' version {version}')

>>say
Out[20]: 'I want to use panda frames in python version 3.8'

It can also be rewritten using ‘\’

>>say=f'I want to use {topic}' \
f' in {lang}' \
f' version {version}'

Python Library Tips: str.format


str.format()

In Python you can format string in a variety of ways.We learned how to use a %format technique in last post. In Python version 2.6 introduced str.format() function which is an improvement over % formatting.

It uses { }, curly braces for replacement fields

spyder_version=3
python_version=2.7
print('I am using Spyder ID {} with Python {}' .format(spyder_version,python_version))

#Output
I am using Spyder ID 3 with Python 2.7

You can access variable using digits starting from {0}-{n} as follows

spyder_version=3
python_version=2.7
print('I am using Python {1} and Spyder IDE {0} for data science ' .format(spyder_version,python_version))

#Output
I am using Python 2.7 and Spyder IDE 3 for data science

Python Library Tips: date formatting


Date formatting

In Python you can format date string using following predefined strings ,

%y/%Y –Year %a/A –Week Day %b/B –Month and %d for day

The letter with lowercase (%y/Y%) gives you abbreviated values, say 20 for 2020, Thu for Thursday etc

>>> print( today.strftime("%y %b %a"))
20 Jun Thu
>>> print( today.strftime("%a,%d,%B,%y "))
Thu,18,June,20 

Locale date

Some times your application may be consumed by people for different localities or people from different countries, of course the date and time will be different. Python allows you to format date and time according to locale settings.

>>> print(today.strftime("%c"))
Thu Jun 18 00:00:00 2020
>>> print(today.strftime("%x"))
06/18/20
>>> print(today.strftime("%X"))

Here %c stand for locale’s date and time , %x for locale’s time and %X for locale’s date

You can also use predefined string s for format time . %I/H for 12/24 Hour, %M for Minutes, %S for second and % p for locales’s AM/PM


Python Library Tips: today()


Today()

Today I want to look around Today function which provided by Standard Python Library. This function can offer much of today’s date. Let’s start with printing what’s today date

from datetime import date
today=date.today()
print(today)

today variable also holding today() properties such as day,year,month,weekday etc. You can use them as follows.

Photo by Pixabay on Pexels.com
print(today.weekday())

weekday gives you number representing week day from 0-6, Monday as first day. You can use the weekday for printing days in a week, Monday or Sunday as first day as follows

wdays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
print('Today is %s ' %wdays[today.weekday()])

Python Library Tips: % formatting


% formatting

In Python you can format string in a variety of ways. Using the % symbol you can place string almost any where.

print('customer A bought %s Quantity of Goods at %s unit price' %(qty,price))

#Output

customer A bought 100 Quantity of Goods at 70 unit price

The conversion types are:

ConversionMeaningNotes
'd'Signed integer decimal.
'i'Signed integer decimal.
'o'Signed octal value.(1)
'u'Obsolete type – it is identical to 'd'.(6)
'x'Signed hexadecimal (lowercase).(2)
'X'Signed hexadecimal (uppercase).(2)
'e'Floating point exponential format (lowercase).(3)
'E'Floating point exponential format (uppercase).(3)
'f'Floating point decimal format.(3)
'F'Floating point decimal format.(3)
'g'Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'G'Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'c'Single character (accepts integer or single character string).
'r'String (converts any Python object using repr()).(5)
's'String (converts any Python object using str()).(5)
'a'String (converts any Python object using ascii()).(5)
'%'No argument is converted, results in a '%' character in the result.
Source : https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting