mirror of
https://github.com/m-lamonaca/dev-notes.git
synced 2025-06-08 10:47:13 +00:00
convert line endings to LF
This commit is contained in:
parent
b74f634cd2
commit
d9d8d55730
9 changed files with 3257 additions and 3257 deletions
|
@ -1,78 +1,78 @@
|
|||
|
||||
# Collections Module
|
||||
|
||||
``` py
|
||||
# COUNTER ()
|
||||
# subclass dictionary for counting hash-capable objects
|
||||
from collections import Counter
|
||||
Counter (sequence) # -> Counter object
|
||||
# {item: num included in sequence, ...}
|
||||
|
||||
var = Counter (sequence)
|
||||
var.most_common (n) # produce list of most common elements (most common n)
|
||||
sum (var.values ()) # total of all counts
|
||||
var.clear () #reset all counts
|
||||
list (var) # list unique items
|
||||
set (var) # convert to a set
|
||||
dict (var) # convert to regular dictionary
|
||||
var.items () # convert to a list of pairs (element, count)
|
||||
Counter (dict (list_of_pairs)) # convert from a list of pairs
|
||||
var.most_common [: - n-1: -1] # n less common elements
|
||||
var + = Counter () # remove zero and negative counts
|
||||
|
||||
|
||||
# DEFAULTDICT ()
|
||||
# dictionary-like object that takes a default type as its first argument
|
||||
# defaultdict will never raise a KeyError exception.
|
||||
# non-existent keys return a default value (default_factory)
|
||||
from collections import defaultdict
|
||||
var = defaultdict (default_factory)
|
||||
var.popitem () # remove and return first element
|
||||
var.popitem (last = True) # remove and return last item
|
||||
|
||||
|
||||
# OREDERDDICT ()
|
||||
# subclass dictionary that "remembers" the order in which the contents are entered
|
||||
# Normal dictionaries have random order
|
||||
name_dict = OrderedDict ()
|
||||
# OrderedDict with same elements but different order are considered different
|
||||
|
||||
|
||||
# USERDICT ()
|
||||
# pure implementation in pythondi a map that works like a normal dictionary.
|
||||
# Designated to create subclasses
|
||||
UserDict.data # recipient of UserDict content
|
||||
|
||||
|
||||
# NAMEDTUPLE ()
|
||||
# each namedtuple is represented by its own class
|
||||
from collections import namedtuple
|
||||
NomeClasse = namedtuple (NomeClasse, parameters_separated_from_space)
|
||||
var = ClassName (parameters)
|
||||
var.attribute # access to attributes
|
||||
var [index] # access to attributes
|
||||
var._fields # access to attribute list
|
||||
var = class._make (iterable) # transformain namedtuple
|
||||
var._asdict () # Return OrderedDict object starting from namedtuple
|
||||
|
||||
|
||||
# DEQUE ()
|
||||
# double ended queue (pronounced "deck")
|
||||
# list editable on both "sides"
|
||||
from collections import deque
|
||||
var = deque (iterable, maxlen = num) # -> deque object
|
||||
var.append (item) # add item to the bottom
|
||||
var.appendleft (item) # add item to the beginning
|
||||
var.clear () # remove all elements
|
||||
var.extend (iterable) # add iterable to the bottom
|
||||
var.extendleft (iterable) # add iterable to the beginning '
|
||||
var.insert (index, item) # insert index position
|
||||
var.index (item, start, stop) # returns position of item
|
||||
var.count (item)
|
||||
var.pop ()
|
||||
var.popleft ()
|
||||
var.remove (value)
|
||||
var.reverse () # reverse element order
|
||||
var.rotate (n) # move the elements of n steps (dx if n> 0, sx if n <0)
|
||||
var.sort ()
|
||||
```
|
||||
|
||||
# Collections Module
|
||||
|
||||
``` py
|
||||
# COUNTER ()
|
||||
# subclass dictionary for counting hash-capable objects
|
||||
from collections import Counter
|
||||
Counter (sequence) # -> Counter object
|
||||
# {item: num included in sequence, ...}
|
||||
|
||||
var = Counter (sequence)
|
||||
var.most_common (n) # produce list of most common elements (most common n)
|
||||
sum (var.values ()) # total of all counts
|
||||
var.clear () #reset all counts
|
||||
list (var) # list unique items
|
||||
set (var) # convert to a set
|
||||
dict (var) # convert to regular dictionary
|
||||
var.items () # convert to a list of pairs (element, count)
|
||||
Counter (dict (list_of_pairs)) # convert from a list of pairs
|
||||
var.most_common [: - n-1: -1] # n less common elements
|
||||
var + = Counter () # remove zero and negative counts
|
||||
|
||||
|
||||
# DEFAULTDICT ()
|
||||
# dictionary-like object that takes a default type as its first argument
|
||||
# defaultdict will never raise a KeyError exception.
|
||||
# non-existent keys return a default value (default_factory)
|
||||
from collections import defaultdict
|
||||
var = defaultdict (default_factory)
|
||||
var.popitem () # remove and return first element
|
||||
var.popitem (last = True) # remove and return last item
|
||||
|
||||
|
||||
# OREDERDDICT ()
|
||||
# subclass dictionary that "remembers" the order in which the contents are entered
|
||||
# Normal dictionaries have random order
|
||||
name_dict = OrderedDict ()
|
||||
# OrderedDict with same elements but different order are considered different
|
||||
|
||||
|
||||
# USERDICT ()
|
||||
# pure implementation in pythondi a map that works like a normal dictionary.
|
||||
# Designated to create subclasses
|
||||
UserDict.data # recipient of UserDict content
|
||||
|
||||
|
||||
# NAMEDTUPLE ()
|
||||
# each namedtuple is represented by its own class
|
||||
from collections import namedtuple
|
||||
NomeClasse = namedtuple (NomeClasse, parameters_separated_from_space)
|
||||
var = ClassName (parameters)
|
||||
var.attribute # access to attributes
|
||||
var [index] # access to attributes
|
||||
var._fields # access to attribute list
|
||||
var = class._make (iterable) # transformain namedtuple
|
||||
var._asdict () # Return OrderedDict object starting from namedtuple
|
||||
|
||||
|
||||
# DEQUE ()
|
||||
# double ended queue (pronounced "deck")
|
||||
# list editable on both "sides"
|
||||
from collections import deque
|
||||
var = deque (iterable, maxlen = num) # -> deque object
|
||||
var.append (item) # add item to the bottom
|
||||
var.appendleft (item) # add item to the beginning
|
||||
var.clear () # remove all elements
|
||||
var.extend (iterable) # add iterable to the bottom
|
||||
var.extendleft (iterable) # add iterable to the beginning '
|
||||
var.insert (index, item) # insert index position
|
||||
var.index (item, start, stop) # returns position of item
|
||||
var.count (item)
|
||||
var.pop ()
|
||||
var.popleft ()
|
||||
var.remove (value)
|
||||
var.reverse () # reverse element order
|
||||
var.rotate (n) # move the elements of n steps (dx if n> 0, sx if n <0)
|
||||
var.sort ()
|
||||
```
|
||||
|
|
|
@ -1,83 +1,83 @@
|
|||
|
||||
# CSV Module
|
||||
|
||||
``` python
|
||||
# iterate lines of csvfile
|
||||
.reader (csvfile, dialect, ** fmtparams) -> reader object
|
||||
|
||||
# READER METHODS
|
||||
.__ next __ () # returns next iterable object line as a list or dictionary
|
||||
|
||||
# READER ATTRIBUTES
|
||||
dialect # read-only description of the dialec used
|
||||
line_num # number of lines from the beginning of the iterator
|
||||
fieldnames
|
||||
|
||||
# convert data to delimited strings
|
||||
# csvfile must support .write ()
|
||||
#type None converted to empty string (simplify SQL NULL dump)
|
||||
.writer (csvfile, dialect, ** fmtparams) -> writer object
|
||||
|
||||
# WRITER METHODS
|
||||
# row must be iterable of strings or numbers or of dictionaries
|
||||
.writerow (row) # write row formatted according to the current dialect
|
||||
.writerows (rows) # write all elements in rows formatted according to the current dialect. rows is iterable of row
|
||||
|
||||
# CSV METHODS
|
||||
# associate dialect to name (name must be string)
|
||||
.register_dialect (name, dialect, ** fmtparams)
|
||||
|
||||
# delete the dialect associated with name
|
||||
.unregister_dialect ()
|
||||
|
||||
# returns the dialect associated with name
|
||||
.get_dialect (name)
|
||||
|
||||
# list of dialects associated with name
|
||||
.list_dialect (name)
|
||||
|
||||
# returns (if empty) or sets the limit of the csv field
|
||||
.field_size_limit (new_limit)
|
||||
|
||||
'''
|
||||
csvfile - iterable object returning a string on each __next __ () call
|
||||
if csv is a file it must be opened with newline = '' (universal newline)
|
||||
dialect - specify the dialect of csv (Excel, ...) (OPTIONAL)
|
||||
|
||||
fmtparams --override formatting parameters (OPTIONAL) https://docs.python.org/3/library/csv.html#csv-fmt-params
|
||||
'''
|
||||
|
||||
# object operating as a reader but maps the info in each row into an OrderedDict whose keys are optional and passed through fieldnames
|
||||
class csv.Dictreader (f, fieldnames = None, restket = none, restval = None, dialect, * args, ** kwargs)
|
||||
'''
|
||||
f - files to read
|
||||
fieldnames --sequence, defines the names of the csv fields. if omitted use the first line of f
|
||||
restval, restkey --se len (row)> fieldnames excess data stored in restval and restkey
|
||||
|
||||
additional parameters passed to the underlying reader instance
|
||||
'''
|
||||
|
||||
class csv.DictWriter (f, fieldnames, restval = '', extrasaction, dialect, * args, ** kwargs)
|
||||
'''
|
||||
f - files to read
|
||||
fieldnames --sequence, defines the names of the csv fields. (NECESSARY)
|
||||
restval --se len (row)> fieldnames excess data stored in restval and restkey
|
||||
extrasaction - if the dictionary passed to writerow () contains key not present in fieldnames extrasaction decides action to be taken (raise cause valueError, ignore ignores additional keys)
|
||||
|
||||
additional parameters passed to the underlying writer instance
|
||||
'''
|
||||
|
||||
# DICTREADER METHODS
|
||||
.writeheader () # write a header line of fields as specified by fieldnames
|
||||
|
||||
# class used to infer the format of the CSV
|
||||
class csv.Sniffer
|
||||
.sniff (sample, delimiters = None) #parse the sample and return a Dialect class. delimiter is a sequence of possible box delimiters
|
||||
.has_header (sample) -> bool # True if first row is a series of column headings
|
||||
|
||||
#CONSTANTS
|
||||
csv.QUOTE_ALL # instructs writer to quote ("") all fields
|
||||
csv.QUOTE_MINIMAL # instructs write to quote only fields containing special characters such as delimiter, quote char ...
|
||||
csv.QUOTE_NONNUMERIC # instructs the writer to quote all non-numeric fields
|
||||
csv.QUOTE_NONE # instructs write to never quote fields
|
||||
```
|
||||
|
||||
# CSV Module
|
||||
|
||||
``` python
|
||||
# iterate lines of csvfile
|
||||
.reader (csvfile, dialect, ** fmtparams) -> reader object
|
||||
|
||||
# READER METHODS
|
||||
.__ next __ () # returns next iterable object line as a list or dictionary
|
||||
|
||||
# READER ATTRIBUTES
|
||||
dialect # read-only description of the dialec used
|
||||
line_num # number of lines from the beginning of the iterator
|
||||
fieldnames
|
||||
|
||||
# convert data to delimited strings
|
||||
# csvfile must support .write ()
|
||||
#type None converted to empty string (simplify SQL NULL dump)
|
||||
.writer (csvfile, dialect, ** fmtparams) -> writer object
|
||||
|
||||
# WRITER METHODS
|
||||
# row must be iterable of strings or numbers or of dictionaries
|
||||
.writerow (row) # write row formatted according to the current dialect
|
||||
.writerows (rows) # write all elements in rows formatted according to the current dialect. rows is iterable of row
|
||||
|
||||
# CSV METHODS
|
||||
# associate dialect to name (name must be string)
|
||||
.register_dialect (name, dialect, ** fmtparams)
|
||||
|
||||
# delete the dialect associated with name
|
||||
.unregister_dialect ()
|
||||
|
||||
# returns the dialect associated with name
|
||||
.get_dialect (name)
|
||||
|
||||
# list of dialects associated with name
|
||||
.list_dialect (name)
|
||||
|
||||
# returns (if empty) or sets the limit of the csv field
|
||||
.field_size_limit (new_limit)
|
||||
|
||||
'''
|
||||
csvfile - iterable object returning a string on each __next __ () call
|
||||
if csv is a file it must be opened with newline = '' (universal newline)
|
||||
dialect - specify the dialect of csv (Excel, ...) (OPTIONAL)
|
||||
|
||||
fmtparams --override formatting parameters (OPTIONAL) https://docs.python.org/3/library/csv.html#csv-fmt-params
|
||||
'''
|
||||
|
||||
# object operating as a reader but maps the info in each row into an OrderedDict whose keys are optional and passed through fieldnames
|
||||
class csv.Dictreader (f, fieldnames = None, restket = none, restval = None, dialect, * args, ** kwargs)
|
||||
'''
|
||||
f - files to read
|
||||
fieldnames --sequence, defines the names of the csv fields. if omitted use the first line of f
|
||||
restval, restkey --se len (row)> fieldnames excess data stored in restval and restkey
|
||||
|
||||
additional parameters passed to the underlying reader instance
|
||||
'''
|
||||
|
||||
class csv.DictWriter (f, fieldnames, restval = '', extrasaction, dialect, * args, ** kwargs)
|
||||
'''
|
||||
f - files to read
|
||||
fieldnames --sequence, defines the names of the csv fields. (NECESSARY)
|
||||
restval --se len (row)> fieldnames excess data stored in restval and restkey
|
||||
extrasaction - if the dictionary passed to writerow () contains key not present in fieldnames extrasaction decides action to be taken (raise cause valueError, ignore ignores additional keys)
|
||||
|
||||
additional parameters passed to the underlying writer instance
|
||||
'''
|
||||
|
||||
# DICTREADER METHODS
|
||||
.writeheader () # write a header line of fields as specified by fieldnames
|
||||
|
||||
# class used to infer the format of the CSV
|
||||
class csv.Sniffer
|
||||
.sniff (sample, delimiters = None) #parse the sample and return a Dialect class. delimiter is a sequence of possible box delimiters
|
||||
.has_header (sample) -> bool # True if first row is a series of column headings
|
||||
|
||||
#CONSTANTS
|
||||
csv.QUOTE_ALL # instructs writer to quote ("") all fields
|
||||
csv.QUOTE_MINIMAL # instructs write to quote only fields containing special characters such as delimiter, quote char ...
|
||||
csv.QUOTE_NONNUMERIC # instructs the writer to quote all non-numeric fields
|
||||
csv.QUOTE_NONE # instructs write to never quote fields
|
||||
```
|
||||
|
|
|
@ -1,72 +1,72 @@
|
|||
# Itertools Module
|
||||
|
||||
``` py
|
||||
# accumulate ([1,2,3,4,5]) -> 1, 3 (1 + 2), 6 (1 + 2 + 3), 10 (1 + 2 + 3 + 6), 15 (1+ 2 + 3 + 4 + 5)
|
||||
# accumulate (iter, func (,)) -> iter [0], func (iter [0] + iter [1]) + func (prev + iter [2]), ...
|
||||
accumulate (iterable, func (_, _))
|
||||
|
||||
# iterator returns elements from the first iterable,
|
||||
# then proceeds to the next until the end of the iterables
|
||||
# does not work if there is only one iterable
|
||||
chain (* iterable)
|
||||
|
||||
# concatenates elements of the single iterable even if it contains sequences
|
||||
chain.from_iterable (iterable)
|
||||
|
||||
# returns sequences of length r starting from the iterable
|
||||
# items treated as unique based on their value
|
||||
combinations (iterable, r)
|
||||
|
||||
# # returns sequences of length r starting from the iterable allowing the repetition of the elements
|
||||
combinations_with_replacement (iterable, r)
|
||||
|
||||
# iterator filters date elements returning only those that have
|
||||
# a corresponding element in selectors that is true
|
||||
compress (data, selectors)
|
||||
|
||||
count (start, step)
|
||||
|
||||
# iterator returning values in infinite sequence
|
||||
cycle (iterable)
|
||||
|
||||
# iterator discards elements of the iterable as long as the predicate is true
|
||||
dropwhile (predicate, iterable)
|
||||
|
||||
# iterator returning values if predicate is false
|
||||
filterfalse (predicate, iterable)
|
||||
|
||||
# iterator returns tuple (key, group)
|
||||
# key is the grouping criterion
|
||||
# group is a generator returning group members
|
||||
groupby (iterable, key = None)
|
||||
|
||||
# iterator returns slices of the iterable
|
||||
isslice (iterable, stop)
|
||||
isslice (iterable, start, stop, step)
|
||||
|
||||
# returns all permutations of length r of the iterable
|
||||
permutations (iterable, r = None)
|
||||
|
||||
# Cartesian product of iterables
|
||||
# loops iterables in order of input
|
||||
# [product ('ABCD', 'xy') -> Ax Ay Bx By Cx Cy Dx Dy]
|
||||
# [product ('ABCD', repeat = 2) -> AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD]
|
||||
product (* iterable, repetitions = 1)
|
||||
|
||||
# returns an object infinite times if repetition is not specified
|
||||
repeat (object, repetitions)
|
||||
|
||||
# iterator compute func (iterable)
|
||||
# used if iterable is pre-zipped sequence (seq of tuples grouping elements)
|
||||
starmap (func, iterable)
|
||||
|
||||
# iterator returning values from iterable as long as predicate is true
|
||||
takewhile (predicate, iterable)
|
||||
|
||||
# returns n independent iterators from the single iterable
|
||||
tee (iterable, n = 2)
|
||||
|
||||
# produces an iterator that aggregates elements from each iterable
|
||||
# if the iterables have different lengths the missing values are filled according to fillervalue
|
||||
zip_longest (* iterable, fillvalue = None)
|
||||
```
|
||||
# Itertools Module
|
||||
|
||||
``` py
|
||||
# accumulate ([1,2,3,4,5]) -> 1, 3 (1 + 2), 6 (1 + 2 + 3), 10 (1 + 2 + 3 + 6), 15 (1+ 2 + 3 + 4 + 5)
|
||||
# accumulate (iter, func (,)) -> iter [0], func (iter [0] + iter [1]) + func (prev + iter [2]), ...
|
||||
accumulate (iterable, func (_, _))
|
||||
|
||||
# iterator returns elements from the first iterable,
|
||||
# then proceeds to the next until the end of the iterables
|
||||
# does not work if there is only one iterable
|
||||
chain (* iterable)
|
||||
|
||||
# concatenates elements of the single iterable even if it contains sequences
|
||||
chain.from_iterable (iterable)
|
||||
|
||||
# returns sequences of length r starting from the iterable
|
||||
# items treated as unique based on their value
|
||||
combinations (iterable, r)
|
||||
|
||||
# # returns sequences of length r starting from the iterable allowing the repetition of the elements
|
||||
combinations_with_replacement (iterable, r)
|
||||
|
||||
# iterator filters date elements returning only those that have
|
||||
# a corresponding element in selectors that is true
|
||||
compress (data, selectors)
|
||||
|
||||
count (start, step)
|
||||
|
||||
# iterator returning values in infinite sequence
|
||||
cycle (iterable)
|
||||
|
||||
# iterator discards elements of the iterable as long as the predicate is true
|
||||
dropwhile (predicate, iterable)
|
||||
|
||||
# iterator returning values if predicate is false
|
||||
filterfalse (predicate, iterable)
|
||||
|
||||
# iterator returns tuple (key, group)
|
||||
# key is the grouping criterion
|
||||
# group is a generator returning group members
|
||||
groupby (iterable, key = None)
|
||||
|
||||
# iterator returns slices of the iterable
|
||||
isslice (iterable, stop)
|
||||
isslice (iterable, start, stop, step)
|
||||
|
||||
# returns all permutations of length r of the iterable
|
||||
permutations (iterable, r = None)
|
||||
|
||||
# Cartesian product of iterables
|
||||
# loops iterables in order of input
|
||||
# [product ('ABCD', 'xy') -> Ax Ay Bx By Cx Cy Dx Dy]
|
||||
# [product ('ABCD', repeat = 2) -> AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD]
|
||||
product (* iterable, repetitions = 1)
|
||||
|
||||
# returns an object infinite times if repetition is not specified
|
||||
repeat (object, repetitions)
|
||||
|
||||
# iterator compute func (iterable)
|
||||
# used if iterable is pre-zipped sequence (seq of tuples grouping elements)
|
||||
starmap (func, iterable)
|
||||
|
||||
# iterator returning values from iterable as long as predicate is true
|
||||
takewhile (predicate, iterable)
|
||||
|
||||
# returns n independent iterators from the single iterable
|
||||
tee (iterable, n = 2)
|
||||
|
||||
# produces an iterator that aggregates elements from each iterable
|
||||
# if the iterables have different lengths the missing values are filled according to fillervalue
|
||||
zip_longest (* iterable, fillvalue = None)
|
||||
```
|
||||
|
|
|
@ -1,64 +1,64 @@
|
|||
# Time & Datetime
|
||||
|
||||
## Time
|
||||
|
||||
```py
|
||||
# epoch: elapsed time in seconds (in UNIX starts from 01-010-1970)
|
||||
import time # UNIX time
|
||||
variable = time.time () # returns the time (in seconds) elapsed since 01-01-1970
|
||||
variable = time.ctime (epochseconds) # transform epoch into date
|
||||
|
||||
var = time.perf_counter () # returns the current running time
|
||||
# execution time = start time - end time
|
||||
```
|
||||
|
||||
### time.srtfrime() format
|
||||
|
||||
| Format | Data |
|
||||
|--------|------------------------------------------------------------------------------------------------------------|
|
||||
| `%a` | Locale's abbreviated weekday name. |
|
||||
| `%A` | Locale's full weekday name. |
|
||||
| `%b` | Locale's abbreviated month name. |
|
||||
| `%B` | Locale's full month name. |
|
||||
| `%c` | Locale's appropriate date and time representation. |
|
||||
| `%d` | Day of the month as a decimal number `[01,31]`. |
|
||||
| `%H` | Hour (24-hour clock) as a decimal number `[00,23]`. |
|
||||
| `%I` | Hour (12-hour clock) as a decimal number `[01,12]`. |
|
||||
| `%j` | Day of the year as a decimal number `[001,366]`. |
|
||||
| `%m` | Month as a decimal number `[01,12]`. |
|
||||
| `%M` | Minute as a decimal number `[00,59]`. |
|
||||
| `%p` | Locale's equivalent of either AM or PM. |
|
||||
| `%S` | Second as a decimal number `[00,61]`. |
|
||||
| `%U` | Week number of the year (Sunday as the first day of the week) as a decimal number `[00,53]`. |
|
||||
| `%w` | Weekday as a decimal number `[0(Sunday),6]`. |
|
||||
| `%W` | Week number of the year (Monday as the first day of the week) as a decimal number `[00,53]`. |
|
||||
| `%x` | Locale's appropriate date representation. |
|
||||
| `%X` | Locale's appropriate time representation. |
|
||||
| `%y` | Year without century as a decimal number `[00,99]`. |
|
||||
| `%Y` | Year with century as a decimal number. |
|
||||
| `%z` | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM |
|
||||
| `%Z` | Time zone name (no characters if no time zone exists). |
|
||||
| `%%` | A literal `%` character. |
|
||||
|
||||
## Datetime
|
||||
|
||||
```py
|
||||
import datetime
|
||||
today = datetime.date.today () # returns current date
|
||||
today = datetime.datetime.today () # returns the current date and time
|
||||
|
||||
# formatting example
|
||||
print ('Current Date: {} - {} - {}' .format (today.day, today.month, today.year))
|
||||
print ('Current Time: {}: {}. {}' .format (today.hour, today.minute, today.second))
|
||||
|
||||
var_1 = datetime.date (year, month, day) # create date object
|
||||
var_2 = datetime.time (hour, minute, second, micro-second) # create time object
|
||||
dt = datetime.combine (var_1, var_2) # combine date and time objects into one object
|
||||
|
||||
date_1 = datetime.date ('year', 'month', 'day')
|
||||
date_2 = date_1.replace (year = 'new_year')
|
||||
|
||||
#DATETIME ARITHMETIC
|
||||
date_1 - date_2 # -> datetime.timedelta (num_of_days)
|
||||
datetime.timedelta # duration expressing the difference between two date, time or datetime objects
|
||||
```
|
||||
# Time & Datetime
|
||||
|
||||
## Time
|
||||
|
||||
```py
|
||||
# epoch: elapsed time in seconds (in UNIX starts from 01-010-1970)
|
||||
import time # UNIX time
|
||||
variable = time.time () # returns the time (in seconds) elapsed since 01-01-1970
|
||||
variable = time.ctime (epochseconds) # transform epoch into date
|
||||
|
||||
var = time.perf_counter () # returns the current running time
|
||||
# execution time = start time - end time
|
||||
```
|
||||
|
||||
### time.srtfrime() format
|
||||
|
||||
| Format | Data |
|
||||
|--------|------------------------------------------------------------------------------------------------------------|
|
||||
| `%a` | Locale's abbreviated weekday name. |
|
||||
| `%A` | Locale's full weekday name. |
|
||||
| `%b` | Locale's abbreviated month name. |
|
||||
| `%B` | Locale's full month name. |
|
||||
| `%c` | Locale's appropriate date and time representation. |
|
||||
| `%d` | Day of the month as a decimal number `[01,31]`. |
|
||||
| `%H` | Hour (24-hour clock) as a decimal number `[00,23]`. |
|
||||
| `%I` | Hour (12-hour clock) as a decimal number `[01,12]`. |
|
||||
| `%j` | Day of the year as a decimal number `[001,366]`. |
|
||||
| `%m` | Month as a decimal number `[01,12]`. |
|
||||
| `%M` | Minute as a decimal number `[00,59]`. |
|
||||
| `%p` | Locale's equivalent of either AM or PM. |
|
||||
| `%S` | Second as a decimal number `[00,61]`. |
|
||||
| `%U` | Week number of the year (Sunday as the first day of the week) as a decimal number `[00,53]`. |
|
||||
| `%w` | Weekday as a decimal number `[0(Sunday),6]`. |
|
||||
| `%W` | Week number of the year (Monday as the first day of the week) as a decimal number `[00,53]`. |
|
||||
| `%x` | Locale's appropriate date representation. |
|
||||
| `%X` | Locale's appropriate time representation. |
|
||||
| `%y` | Year without century as a decimal number `[00,99]`. |
|
||||
| `%Y` | Year with century as a decimal number. |
|
||||
| `%z` | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM |
|
||||
| `%Z` | Time zone name (no characters if no time zone exists). |
|
||||
| `%%` | A literal `%` character. |
|
||||
|
||||
## Datetime
|
||||
|
||||
```py
|
||||
import datetime
|
||||
today = datetime.date.today () # returns current date
|
||||
today = datetime.datetime.today () # returns the current date and time
|
||||
|
||||
# formatting example
|
||||
print ('Current Date: {} - {} - {}' .format (today.day, today.month, today.year))
|
||||
print ('Current Time: {}: {}. {}' .format (today.hour, today.minute, today.second))
|
||||
|
||||
var_1 = datetime.date (year, month, day) # create date object
|
||||
var_2 = datetime.time (hour, minute, second, micro-second) # create time object
|
||||
dt = datetime.combine (var_1, var_2) # combine date and time objects into one object
|
||||
|
||||
date_1 = datetime.date ('year', 'month', 'day')
|
||||
date_2 = date_1.replace (year = 'new_year')
|
||||
|
||||
#DATETIME ARITHMETIC
|
||||
date_1 - date_2 # -> datetime.timedelta (num_of_days)
|
||||
datetime.timedelta # duration expressing the difference between two date, time or datetime objects
|
||||
```
|
||||
|
|
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue