python笔记:时间,排序 # 一个基本的排序算法 ```python # -- coding: utf-8 -- import random import time num_list = [] for i in xrange(1,10000): num_list.append(random.randint(1, 9999)) t = time.time() num_list.sort(lambda x,y:cmp(y,x)) #自己实现cmp函数可以实现自定义的排序器,本例是逆序 print(time.time() - t) ``` ## python3实现 ``` #python3 中取消了sort的传参,使用key做为排序依据 #把学号按先按字母正序,再按数字逆序排列,a在b前,9在1前 stu_no = ["a001","y008","b003","a009","b004"] stu_no.sort(key=lambda x:x[1:4],reverse=True) print(stu_no) stu_no.sort(key=lambda x:x[0:1]) print(stu_no) # 第二种实现方式 names = ["a001","y008","b003","a009","b004"] a_before_z = lambda x: str.isalpha(x) and ord(x) nine_before_zero = lambda x: str.isdigit(x) and -int(x) result = sorted(names, key=lambda x: (a_before_z(x[:1]), nine_before_zero(x[1:]) )) # 输出 ['a009', 'a001', 'b004', 'b003', 'y008'] ``` # 时间 ## 使用datetime 创建时间对象 ``` val = datetime.datetime(2014,11,11,12,12,12) #2012-11-11 12:12:12 ``` ## 获取当前时间前三天的时间 ```python nowtime = datetime.datetime.now() before3Day = nowtime + datetime.timedelta(days=-3) ``` ## 比较两个时间的前后 ``` print(val < before3Day) #注意,必须类型相同才能用小于号比较 ``` ## 时间格式化 ``` # -- coding: utf-8 -- import datetime, time temp_datetime = datetime.datetime.strptime("20090101 121212", "%Y%m%d %H%M%S") timestamp = temp_datetime.timestamp() print(timestamp) # 1230783132.0 temp_datetime2 = datetime.datetime.fromtimestamp( float("1230783132.0") ).strftime('%Y-%m-%d %H:%M:%S') print(temp_datetime2) # 2009-01-01 12:12:12 #星期 def weekday(input): weekday_arr = [u"星期一", u"星期二", u"星期三", u"星期四", u"星期五", u"星期六", u"星期日", ] return weekday_arr[input] weekday(item.timestamp.weekday()) ``` ### 时间格式化参数 ```bash %a -> Sun %A -> Sunday %b -> May %B -> May %c -> Sun May 24 05:21:18 1970 %d -> 24 %f -> 000000 %H -> 05 %I -> 05 %j -> 144 %m -> 05 %M -> 21 %p -> AM %S -> 18 %U -> 21 %w -> 0 %W -> 20 %x -> 05/24/70 %X -> 05:21:18 %y -> 70 %Y -> 1970 %z -> %Z -> %% -> % ``` ## 时区 真是蛋疼啊。 ``` from datetime import datetime from dateutil import tz # METHOD 1: Hardcode zones: from_zone = tz.gettz('UTC') to_zone = tz.gettz('America/New_York') # METHOD 2: Auto-detect zones: from_zone = tz.tzutc() to_zone = tz.tzlocal() # utc = datetime.utcnow() utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S') # Tell the datetime object that it's in UTC time zone since # datetime objects are 'naive' by default utc = utc.replace(tzinfo=from_zone) # Convert time zone central = utc.astimezone(to_zone) ``` ## 使用UTC time 在应用中,应该尽可能使用utc time。 `time.time()`产生的timestamp是utc为基准的。不包含时区信息。 或者使用:`datetime.datetime.utcnow()`。 建议使用timestamp,返回给前端。在数据库中使用int保存timestamp。这样可以省很多功夫。 来自 大脸猫 写于 2016-05-17 15:04 -- 更新于2020-10-19 13:06 -- 0 条评论