Skip to content

Instantly share code, notes, and snippets.

@dketov
Created December 14, 2011 12:52
Show Gist options
  • Save dketov/1476462 to your computer and use it in GitHub Desktop.
Save dketov/1476462 to your computer and use it in GitHub Desktop.
Полезные утилиты
# -*- encoding: utf-8 -*-
"""
Поверхностное и глубокое копирование
"""
import copy
listOne = [{"name": "Willie", "city": "Providence, RI"}, 1, "tomato", 3.0]
listTwo = listOne[:]
listTwo=copy.copy(listOne)
listThree = copy.deepcopy(listOne)
listOne.append("kid")
listOne[0]["city"] = "San Francisco, CA"
print listOne
print listTwo
print listThree
# -*- encoding: utf-8 -*-
"""
Интервалы времени
"""
from datetime import timedelta
year = timedelta(days=365)
another_year = timedelta(weeks=40, days=84, hours=23, minutes=50, seconds=600) # adds up to 365 days
year == another_year
ten_years = 10 * year
ten_years, ten_years.days // 365
nine_years = ten_years - year
nine_years, nine_years.days // 365
three_years = nine_years // 3;
three_years, three_years.days // 365
abs(three_years - ten_years) == 2 * three_years + year
# -*- encoding: utf-8 -*-
"""
Текущее время
"""
import time
from datetime import date
today = date.today()
today
datetime.date(2007, 12, 5)
today == date.fromtimestamp(time.time())
my_birthday = date(today.year, 6, 24)
if my_birthday < today:
my_birthday = my_birthday.replace(year=today.year + 1)
my_birthday
datetime.date(2008, 6, 24)
time_to_birthday = abs(my_birthday - today)
time_to_birthday.days
# -*- encoding: utf-8 -*-
"""
Календарь
"""
import calendar
month = 3
year = 2010
monthMatrix = calendar.monthcalendar(year, month)
# print out the heading
print "%s %d\n" % (calendar.month_name[month], year)
# print out each day in hex; if the day = 0, then leave it blank
for week in monthMatrix:
for day in week:
if day == 0:
print " ",
else:
print "%2s" % (hex(day)[2:]),
print
# -*- encoding: utf-8 -*-
"""
Псевдослучайные числа
"""
import random
random.random() # Random float x, 0.0 <= x < 1.0
random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0
random.randint(1, 10) # Integer from 1 to 10, endpoints included
random.randrange(0, 101, 2) # Even integer from 0 to 100
random.choice('abcdefghij') # Choose a random element
items = [1, 2, 3, 4, 5, 6, 7]
random.shuffle(items)
print items
random.sample([1, 2, 3, 4, 5], 3) # Choose 3 elements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment