Tag Archives: Python Lessons

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: 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

Create Covid-19 data list using Python in 5 minute


This tutorial will tell how you can create a quick list of Covid-19 pandemic real time data list using simple Python Scrip.

For this we are using data API provided by CovidTracking.com. Our example relay on the JSON data file which offer an up to dated covid-19 data set.

Web Request and urllib2

First we need a web request and bring all the JSON object from the internet. Using urllib2 standard Python library we can fetch the web content as follows.

urldata = 'https://covidtracking.com/api/v1/states/current.json'
    weburl = urllib2.urlopen(urldata)
    print("result code :" + str(weburl.getcode()))
    if (weburl.getcode() == 200):
        data = weburl.read()
        printData(data)
    else:
        print "Some server related error occurs"
PYTHON SPIDER IDE