2018. január 16., kedd

Gyorskeresés

python tippek tricks

Írta: | Kulcsszavak: python . os.path . time conversion . range

[ ÚJ BEJEGYZÉS ]

Mindenféle csuda kiegészítő:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python

os.path
exists(),isdir(),isfile()
Ezek a függvények követik a symlinkeket, tehát ha fontos, hogy a kapott file elérési út valós-e
és nem egy linkről van szó. akkoor igy tudjuk leellenőrizni
if isfile(path) and not islink(path)

lexists() - symlinkre True-t ad vissz
-------------------------------------------------------
Manipulating paths
basename() - a path utolsó könyvtárát adja vissza
>>> os.path.basename ("d:\\down\\linux")
'linux'
dirname() - path-basename -t adja vissza
>>> os.path.dirname ("d:\\down\\linux")
'd:\\down'

>>> os.path.isabs ("down\\linux")
False
>>> os.path.isabs ("d:\\down\\linux")
True

abspath() - a normalizált path-ot adja vissza
>>> os.path.abspath ("down\\linux")
'C:\\Python25\\down\\linux'

-------------------------------------------------------
Building paths

Ahhoz, hogy igazán platform függetlenül dolgozzunk a pathot célszerű az join() összerakni
Egyszerűbb, mint stringenként.
>>> os.path.join("d:\\","down","linux")
'd:\\down\\linux'

Ha szükséges, hogy az elérési út végén legyen '\' akkor egészitsük ki a parancsot egy "" paraméterrel
>>> os.path.join("d:\\","down","linux","")
'd:\\down\\linux\\'

-------------------------------------------------------
Slash and back and case sensitivity

normpath() és abspath() konvertálja a "pereket" az adott os-nek megfelelően.
strpath = 'Documents/Letters'
normpath(strpath)
- linuxon: Documents/Letters
- windowson: Documents\\Letters

Míg a Windows-os filerendszerek (FAT,NTFS) ellenben a Linuxosokkal (ext) nem case sensitivek.
De linux alá van lehetőség felmountolni nem Case Sensitiv filerendszereket ezért ebben az esetben jó hasznát vesszük a normcase-nek.
if os.path.normcase('yY')==os.path.normcase('yy'): print 'windows
else: print 'linux'

---------------------------------------------------------------------------------------------------------------------

Python time convesion

datetime to time tuple

>>> dt = datetime.datetime(2010, 12, 31, 23, 59, 59)
>>> tt = dt.timetuple()
>>> print tt
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, tm_hour=23,
tm_min=59, tm_sec=59, ...)

datetime to time stamp

>>> dt = datetime.datetime(2010, 12, 31, 23, 59, 59)
>>> ts = time.mktime(dt.timetuple())
>>> print ts
1293868799.0

datetime to string

>>> dt = datetime.datetime(2010, 12, 31, 23, 59, 59)
>>> st = dt.strftime('%Y-%m-%d %H:%M:%S')
>>> print st
2010-12-31 23:59:59

time tuple to datetime

>>> tt = (2010, 12, 31, 23, 59, 59, 4, 365, 0)
>>> dt = datetime.datetime(tt[0], tt[1], tt[2], tt[3], tt[4], tt[5])
>>> print dt
2010-12-31 23:59:59
>>>
>>> dt = datetime.datetime(*tt[0:6]) # same with the code above
>>> print dt
2010-12-31 23:59:59

time tuple to time stamp

>>> tt = (2010, 12, 31, 23, 59, 59, 4, 365, 0)
>>> ts = time.mktime(tt)
>>> print ts
1293868799.0

time tuple to string

>>> tt = (2010, 12, 31, 23, 59, 59, 4, 365, 0)
>>> st = time.strftime('%Y-%m-%d %H:%M:%S', tt)
>>> print st
2010-12-31 23:59:59

time stamp to datetime

>>> ts = 1293868799.0
>>> dt = datetime.datetime.fromtimestamp(ts) # for local time
>>> print dt
2010-12-31 23:59:59
>>>
>>> dt = datetime.datetime.utcfromtimestamp(ts) # for UTC
>>> print dt
2011-01-01 07:59:59

time stamp to time tuple

>>> ts = 1293868799.0
>>> tt = time.localtime(ts)
>>> print tt
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, tm_hour=23,
tm_min=59, tm_sec=59, ...)
>>>
>>> tt = time.gmtime(ts)
>>> print tt
time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=7,
tm_min=59, tm_sec=59, ...)

time stamp to string

>>> ts = 1293868799.0
>>> st = datetime.datetime.fromtimestamp(ts).strftime(
... '%Y-%m-%d %H:%M:%S')
>>> print st
2010-12-31 23:59:59
>>>
>>> st = datetime.datetime.utcfromtimestamp(ts).strftime(
... '%Y-%m-%d %H:%M:%S')
>>> print st
2011-01-01 07:59:59

string to datetime

>>> s = '2010-12-31 23:59:59'
>>> dt = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
>>> print dt
2010-12-31 23:59:59

string to time tuple

>>> st = '2010-12-31 23:59:59'
>>> tt = time.strptime(st, '%Y-%m-%d %H:%M:%S')
>>> print tt
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, tm_hour=23,
tm_min=59, tm_sec=59, ...)

string to time stamp

>>> s = '2010-12-31 23:59:59'
>>> ts = time.mktime(time.strptime(s, '%Y-%m-%d %H:%M:%S'))
>>> print ts
1293868799.0

seconds_to_hhmmss
def format_seconds_to_hhmmss(seconds):
hours = seconds // (60*60)
seconds %= (60*60)
minutes = seconds // 60
seconds %= 60
return "%02i:%02i:%02i" % (hours, minutes, seconds)

>>> format_seconds_to_hhmmss(99*hours + 15*minutes + 30) == "99:15:30"

hh:mm:ss to seconds
def format_strhhmmss_to_sec(strtime):
strt=strtime.split(':')
hours = int(strt[0]) * (60*60)
minutes = int(strt[1]) * 60
seconds = int(strt[2])
return (int(hours)+int(minutes)+int(seconds))

-----------------------------------------------------------------------------------------------

range() vs xrange()

2.x verzióknál nagy range-k esetén erősen javasolt az xrange használata.
Gyorsabb és a lefoglalt memóriával is jobban gazdálkodik.
3.x verziótól már csak range() van, de az xrange minden előnyével.
import time

rangestart=time.time()
for i in range(1000000):
pass
rangeend=time.time()
xrangestart=time.time()
for i in xrange(1000000):
pass
xrangeend=time.time()

print "range:", rangeend-rangestart
print "xrange:", xrangeend-xrangestart

range: 0.081
xrange: 0.053

-------------------------------------------------------------------------------------------------

set

>>> example=set([1,2,3,4])
>>> example
set([1, 2, 3, 4])

>>> example.add(6)
>>> example
set([1, 2, 3, 4, 6])

>>> example.clear()
>>> example
set([])

>>> example=set([1,2,3,4])
>>> example|set([5,6,7,8])
set([1, 2, 3, 4, 5, 6, 7, 8])

# set-ek osszeadasa / unioja, hasonlo, mint az OR bit muvelet
>>> example|set([5,6,7,8])
>>> example.union(set([5,6,7,8]))
set([1, 2, 3, 4, 5, 6, 7, 8])

# set-k AND kapcsolata
>>> example=set([1,2,3,4,5,6])
>>> example&set([5,6])
>>> example.intersection(set([5,6]))
set([5, 6])

# set-ek kulonbsege
>>> example=set([1,2,3,4,5,6])
>>> example-set([5,6])
>>> example.difference(set([5,6]))
set([1, 2, 3, 4])

# set XOR v symmetric_difference()
>>> example=set([1,2,3,4,5])
>>> example.symmetric_difference(set([4,5,6]))
set([1, 2, 3, 6])

# set issubset - az elso set elemei benne vannak-e a masodik set-ben
>>> set([1,2,3,4,5]).issubset([1,2,3])
False
>>> set([1,3,2]).issubset([1,2,3,4,5])
True

# set issuperset - issubset inverze. A masodik set elemei benne vannak-e az elso set-ben
>>> set([1,3,2]).issuperset([1,2,3,4,5])
False
>>> set([1,3,2,4,5]).issuperset([1,2,3])
True

Copyright © 2000-2018 PROHARDVER Informatikai Kft.