python 图片对比的时间怎么对比

下面介绍下Python中比较两个日期大小的脚本.
在实际工作中用到,以供后续参考及备忘
时间区间比较函数
import time
# 这里比较l_time 是否在时间区间[start_t, end_t]中
def compare_time(l_time,start_t,end_t):
& & s_time = time.mktime(time.strptime(start_t,'%Y%m%d%H%M')) # get the seconds for specify date
& & e_time = time.mktime(time.strptime(end_t,'%Y%m%d%H%M'))
& & log_time = time.mktime(time.strptime(l_time,'%Y-%m-%d %H:%M:%S'))
& & if (float(log_time) &= float(s_time)) and (float(log_time) &= float(e_time)):
& & & & return True
& & return False
# 在用mktime时,注意import time 模块,否则会提示找不到改attribute. & 输入的时间格式必须跟自己的格式化串保持一致.
如时间: & 14:56:58& &定义格式串时应该为: &%Y-%m-%d %H:%M:%S&
有试过 from datetim import datetime,time , 但是没有成功,暂时没有考虑去解决.
本文已收录于以下专栏:
相关文章推荐
$dayOfYear: 返回该日期是这一年的第几天。(全年366天)
$dayOfMonth: 返回该日期是这一个月的第几天。(1到31)
$dayOfWeek: 返回的是这个周的星期几。(1:星期日...
Python时间和日期操作需要用到datetime和time标准库模块。
一、time模块
1.time模块表示时间的方式
②格式化的时间字符串
③以数组的形式表示,即(stru...
1、获取日期列表
/Users/nisj/PycharmProjects/EsDataProc/bi-static/date_list.py
# -*- coding=utf-8 -*-
from sklearn.datasets import load_boston
boston = load_boston()
print(boston.DESCR)
#导入model_select...
Pyhton 
本文转自/goodspeed/点击打开链接
#! /usr/bin/python
# coding=utf-8
import ...
导入包:from operator import itemgetterfrom itertools import groupbyrlst是一个而为list 如:[[&a1&,20,&b1&,&c1&]...
mysql如何遍历某个字段所有值并计算比例解决问题1.构造数据
INSERT INTO `test`.`test` (`id`, `num`, `num2`, `branch_id`, `o...
import timetime模块中主要有一下方法
time.time() 获取当前系统时间,返回float型数值时间戳(当前时间相对于 00:00:00 以秒计算的偏移量)
在Shell中我们可以利用date命令比较两个日期的大小,方法是先把日期转换成时间戳格式,再进行比较。
date 的+%s可以将日期转换成时间戳格式,看下面的例子:
#!/bin/bash 
Python比较2个时间的大小Python中有time和datetime,不过二者都直接取出日期和时间。
当需要比较2个时间的先后时,这两个类的函数都显得有些过于复杂。因为它们都带上了日期。如果仅想...
他的最新文章
讲师:吴岸城
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)帐号:密码:下次自动登录{url:/nForum/slist.json?uid=guest&root=list-section}{url:/nForum/nlist.json?uid=guest&root=list-section}
贴数:2&分页:'精灵射手','猥琐大叔'发信人: elf (噢莉芙,爱宝宝,爱魔方,爱Python), 信区: Python
标&&题: 关于python时间比较的问题请教一下高手
发信站: 水木社区 (Fri Nov 23 13:24:06 2012), 转信 && from dateutil.parser import parse as dateparse,datetime && dateparse('Thu, 22 Nov :46 GMT')&datetime.datetime.utcnow() && 结果:
TypeError: can't compare offset-naive and offset-aware datetimes && 把GMT砍掉是可以正常比较的
dateparse('Thu, 22 Nov :46')&datetime.datetime.utcnow()
Out[39]: False && 如果时区是UTC或GMT我把它砍掉不会影响结果,
但是有没有什么办法可以直接比较带时区的时间字符串与utcnow?
我昨天google了好久,也没弄明白,求助各位了. && --
§●╔═╗║免║║封║║金║║牌║╚═╝§■◢◢&&&&◤&&&&&& ◣&&&&◤&&&&&&&&◣&& &&&&&&&&&&&&&&︵_.︿._︵&&&&&&◣◣&&&& &&&& ★&&&&◤&& && &&&&&&&& 〈~~~┄( ★ )┄~~~〉&&&&◤&&&&&&◣ &&▊ ┃◤&&&&&& && &&&&&&&&&& ~~~︶ `﹀' ︶~~~&&▊ ●&&&&●&& && &&●&&&&●&&&& &&&&◣&&︶&& ◤ ▊&&◣&&﹀&&◤▎&&&&&&&&持 证 人&& xiaoya&&elf&&&&&&◢▄◣&&&& &&&& ◢▄◣&&&&&& && ※ 来源:·水木社区 newsmth.net·[FROM: My Heart & Soul] &&&& ※ 来源:·水木社区 newsmth.net·[FROM: 106.3.242.*]
'精灵射手','猥琐大叔'发信人: elf (噢莉芙,爱宝宝,爱魔方,爱Python), 信区: Python
标&&题: Re: 关于python时间比较的问题请教一下高手
发信站: 水木社区 (Fri Nov 23 13:56:04 2012), 转信 && 找到了pytz,貌似可以搞定了
来自网上的例子
import datetime
import pytz
utc=pytz.UTC
unaware = datetime.datetime(,8,15,12,0)
aware = datetime.datetime(,8,15,12,0,utc) && now_aware = utc.localize(unaware)
assert aware == now_aware && 【 在 elf (噢莉芙,爱宝宝,爱魔方,爱Python) 的大作中提到: 】
: from dateutil.parser import parse as dateparse,datetime
: dateparse('Thu, 22 Nov :46 GMT')&datetime.datetime.utcnow()
: ...................
§●╔═╗║免║║封║║金║║牌║╚═╝§■◢◢&&&&◤&&&&&& ◣&&&&◤&&&&&&&&◣&& &&&&&&&&&&&&&&︵_.︿._︵&&&&&&◣◣&&&& &&&& ★&&&&◤&& && &&&&&&&& 〈~~~┄( ★ )┄~~~〉&&&&◤&&&&&&◣ &&▊ ┃◤&&&&&& && &&&&&&&&&& ~~~︶ `﹀' ︶~~~&&▊ ●&&&&●&& && &&●&&&&●&&&& &&&&◣&&︶&& ◤ ▊&&◣&&﹀&&◤▎&&&&&&&&持 证 人&& xiaoya&&elf&&&&&&◢▄◣&&&& &&&& ◢▄◣&&&&&& && ※ 来源:·水木社区 newsmth.net·[FROM: My Heart & Soul] &&&& ※ 来源:·水木社区 newsmth.net·[FROM: 106.3.242.*]
文章数:2&分页:用户名:kuangling
文章数:59
评论数:234
访问量:287191
注册日期:
阅读量:1297
阅读量:3317
阅读量:582850
阅读量:467797
51CTO推荐博文
&&&&&&&&&由于自己是负责海外项目,常常会遇到一些问题,最近被系统时间与mysql时间不在一个时区,而坑了自己,一般修改了系统时区之后,MySQL必须重启,不然MySQL时区是不对的,会导致数据全部都是错的~~~,哎,只有坑到了自己,才会想到要去避免这种事情再次出现,所以用python写了一个简单判断时区的脚本,时区不对并邮件发出来,大家参考参考,详情如下:1、脚本实例#!/usr/bin/env&python
#&coding=utf8
#&auther:kuangl
#&This&is&system&time&and&sql&time&diff
from&&datetime&&import&&*
import&os,sys,socket,fcntl,struct
import&MySQLdb
import&smtplib
from&email.mime.multipart&import&MIMEMultipart
from&email.mime.base&import&MIMEBase
from&email.mime.text&import&MIMEText
reload(sys)
sys.setdefaultencoding('utf8')
'''定义发送邮件函数'''
def&sendmail(html,emailaddress,mailSubject,from_address=""):
&&&&&&&&mail_list=emailaddress.split(",")
&&&&&&&&msg=MIMEMultipart()
&&&&&&&&msg['Accept-Language']='zh-CN'
&&&&&&&&msg['Accept-Charset']=&'ISO-8859-1,utf-8'
&&&&&&&&msg['From']=from_address
&&&&&&&&msg['to']=";".join(mail_list)
&&&&&&&&msg['Subject']=mailSubject.decode("utf-8")
&&&&&&&&txt=MIMEText(html,'html','utf-8')
&&&&&&&&txt.set_charset('utf-8')
&&&&&&&&msg.attach(txt)
&&&&&&&&smtp=smtplib.SMTP("")
&&&&&&&&smtp.sendmail(msg["From"],mail_list,msg.as_string())
&&&&&&&&smtp.close()
'''查看本机hostname'''
hostname=socket.gethostname()
print&hostname
'''查看本机IP地址'''
def&get_ip_address(ifname):
&&&&s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
&&&&return&socket.inet_ntoa(fcntl.ioctl(
&&&&&&&&&&&&s.fileno(),
&&&&&&&&&&&&0x8915,
&&&&&&&&&&&&struct.pack('256s',ifname[:15])
&&&&)[20:24])
ip_add&=&get_ip_address('eth0')
print&ip_add
'''查看系统时间'''
nowtime&=&datetime.now()
daytime&=&nowtime.strftime('%Y-%m-%d&%H:%M')
print&'system&time&time:',&daytime
'''查看数据库时间'''
SQL='select&now()'
def&mysql_connect(sql,host):
&&&&&&&&conn=MySQLdb.connect(host='127.0.0.1',user='rd',passwd=pwd,port=3306)
&&&&&&&&cur=conn.cursor()
&&&&&&&&cur.execute(sql)
&&&&&&&&result=cur.fetchall()
&&&&&&&&cur.close()
&&&&&&&&conn.close()
&&&&&&&&return&result
&&&&except&MySQLdb.Error,e:
&&&&&&&&print&"Mysql&Error&%d:&%s"&%&(e.args[0],e.args[1])
server_result=mysql_connect(sql=SQL,host='127.0.0.1')
sql_gettime=server_result[0][0]
SQLTime=sql_gettime.strftime('%Y-%m-%d&%H:%M')
print&'SQL&server&time:',SQLTime
'''&定义邮件参数'''
Content=&'Dear&ALL:&&br&&&&&'&+&ip_add&+&'&,&System&and&Database&time&error,&&br&&&&&System&time&is&:&'+&daytime&+'&&br&&&&&Database&time&is&:&'&+&SQLTime&+&'&&br&&&&&Please&check&all&time!&&br&&&&&&br&&&&&Friendly&reminder,Please&note!'
Subject=&'[监控][海外时区监控]['&+&hostname&+&']System&and&Database&time&error'
'''&判断时间是否相等'''
if&daytime&==&SQLTime:
&&&&print&"system&and&sql&time&is&OK,&not&sednemail"
&&&&print&"system&and&sql&time&is&Fail,Start&email&to&all"
&&&&sendmail(html=Content,emailaddress='',mailSubject=Subject)2、测试结果本文出自 “” 博客,请务必保留此出处
了这篇文章
类别:┆阅读(0)┆评论(0)
09:33:31 16:29:50博客分类:
周末抽空做了点小测试,根据/jzhang/archive//18807.html中m网友修改的算法,python版本中读取所有行以后就做一个排序,再去除重复项。这个算法在我的机器上执行时间是1735ms左右,属于python版本中最快的一个。D版本暂还没想到有更优化的做法,D在处理以char[]作key的关联数组时,判断方法是先判断hash,如果hash相等,则继续做字符串判断。它执行时间是1120ms左右。以D版本为基础,自己写了一个C++的Email类:&!---->class Email{private:
friend bool operator & (const Email& lhs, const Email& rhs);public:
Email (const char* mail_)
: mail(mail_), hash(my_hash(mail_))
}};bool operator & (const Email& lhs, const Email& rhs){
if (lhs.hash == rhs.hash)
return lhs.mail & rhs.
return lhs.hash & rhs.}把它插入set并判断是否有重复。这个程序由于string的大量拷贝,以及大量内存分配,执行时间相当长,在我的机器上是5s左右。D和python版本由于对象拷贝成本较低,加上都有内存分配策略,自然有一些优势。退而求其次,既然hash冲突的几率较低,试试只保存hash:&!---->class Email{private:
friend bool operator & (const Email& lhs, const Email& rhs);public:
Email (const char* mail_)
: hash(my_hash(mail_))
}};bool operator & (const Email& lhs, const Email& rhs){
return lhs.hash & rhs.}这次测试就比较快了,耗时仅1020ms左右,比D版本还要快,当然它不是完善的版本。考虑到构造成本,于是改为只用一个set&int&来保存hash值再测试,这次耗时是930ms。实际上可以做一个改进的C++版本,一次性读入文件的全部内容到一个大缓冲区,把所有的\n字符修改为\0,用一个动态数组保存缓冲区的所有字符串指针,hash值也须计算并保存到数组。再用D的索引方式,先hash比较,再字符串比较,效率应该也不低。实现了一个:&!---->#include &iostream&#include &string&#include &set&#include &fstream&#include &iterator&#include &sys/time.h&using namespacesize_t my_hash (const char* str){
size_t ret = 0;
while (*str)
ret = 11 * ret + *str++;
return}class Email{private:
const char*
friend bool operator & (const Email& lhs, const Email& rhs);public:
Email (const char* mail_)
: hash(my_hash(mail_)), mail(mail_)
}};bool operator & (const Email& lhs, const Email& rhs){
if (lhs.hash == rhs.hash)
return strcmp(lhs.mail, rhs.mail) & 0;
return lhs.hash & rhs.}int main(int argc, char** argv){
if (argc & 3)
cout && "Wrong arguments" &&
FILE* fin = fopen(argv[1], "r");
cout && "Invalid input file" &&
FILE* fout = fopen(argv[2], "w");
if (!fout)
fclose(fin);
cout && "Invalid output file" &&
timeval start,
const int BUF_SIZE = 20 * 1024 * 1024;
char* buffer = new char[BUF_SIZE];
memset(buffer, 0, BUF_SIZE);
gettimeofday(&start, 0);
set&Email&
size_t read = fread (buffer, BUF_SIZE, 1, fin);
char* begin =
char* current =
while (*current != '\0')
if (*current == '\n')
*current = '\0';
if (emails.insert(begin).second){
fputs(begin, fout);
fwrite("\n", 1, 1, fout);
begin = current + 1;
fclose(fout);
fclose(fin);
gettimeofday(&end, 0);
printf("Time used: %d ms\n", ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000));
return 0;}memset不是必须的,不过我不知道如何获取读入的大小。fread读取后,如果读到EOF,则返回值为0。所以我这里用memset先初始化内存,但不把它计入耗时。new操作也没计入,因为其它语言比如python、D在启动时都由运行时做了类似工作。这个程序在我的机器上耗时为1350ms左右。我想可慢在set上,对象拷贝?内存分配?做了几个优化版本,没多大提高。
重新测试了下:A、python(m网友版本):lijie t #
test.pylijie t #
test.py1lijie t #
test.py9lijie t #
test.py1lijie t #
test.pyB、D版本:lijie t # ./testd email.txt email-new.txt1091lijie t # ./testd email.txt email-new.txt1070lijie t # ./testd email.txt email-new.txt1062lijie t # ./testd email.txt email-new.txt1062lijie t # ./testd email.txt email-new.txt1096C、C++只比较hash,set&Email&版本:lijie t # ./test3 email.txt email-new.txtTime used: 981 mslijie t # ./test3 email.txt email-new.txtTime used: 1000 mslijie t # ./test3 email.txt email-new.txtTime used: 980 mslijie t # ./test3 email.txt email-new.txtTime used: 986 mslijie t # ./test3 email.txt email-new.txtTime used: 987 msD、C++只比较hash,set&int&版本:lijie t # ./test4 email.txt email-new.txtTime used: 951 mslijie t # ./test4 email.txt email-new.txtTime used: 953 mslijie t # ./test4 email.txt email-new.txtTime used: 947 mslijie t # ./test4 email.txt email-new.txtTime used: 950 mslijie t # ./test4 email.txt email-new.txtTime used: 962 msE、C++大缓冲区,比较hash和字符串,set&Email&版本:lijie t # ./test5 email.txt email-new.txtTime used: 1375 mslijie t # ./test5 email.txt email-new.txtTime used: 1359 mslijie t # ./test5 email.txt email-new.txtTime used: 1369 mslijie t # ./test5 email.txt email-new.txtTime used: 1378 mslijie t # ./test5 email.txt email-new.txtTime used: 1396 msF、C++大缓冲区,比较字符串版本:lijie t # ./test6 email.txt email-new.txtTime used: 1168 mslijie t # ./test6 email.txt email-new.txtTime used: 1169 mslijie t # ./test6 email.txt email-new.txtTime used: 1171 mslijie t # ./test6 email.txt email-new.txtTime used: 1179 mslijie t # ./test6 email.txt email-new.txtTime used: 1169 ms从C、E和F来看,对象拷贝成本是比较高的,E版本仅仅比C版本多了个const char*成员变量,hash值比较散,很少会真的执行到strcmp。保持E版本对象结构不变,把operator &里面的实现改为C版本,测试结果如下:lijie t # ./test5 email.txt email-new.txtTime used: 1355 mslijie t # ./test5 email.txt email-new.txtTime used: 1360 mslijie t # ./test5 email.txt email-new.txtTime used: 1348 mslijie t # ./test5 email.txt email-new.txtTime used: 1353 mslijie t # ./test5 email.txt email-new.txtTime used: 1379 ms效率只提高了一点点,这个版本仅仅比C版本多了个成员变量拷贝,竟然慢了这么多。说明Email对象的2个成员变量拷贝成本的确很高。F版本相比之下反而效率很不错,主要原因是email数据不够复杂,仅通过前几位就可以比较出结果。如果每行数据比较长,而且很多行要到后几个字符才能比较出来,肯定就不那么快了。hash值的计算虽然执行了一系列乘法,不过还是相当迅速。D语言版本执行了hash值和字符串比较,是比较完善的,效率很不错。C++相应版本看来要提高set的效率才能达到。
jzhang的第一个python版本在我的机器上执行如下:lijie t #
test2.py mslijie t #
test2.py2 mslijie t #
test2.py9 mslijie t #
test2.py5 mslijie t #
test2.py1 ms我做了点修改,执行速度提高了一些:&!---->#remove duplicated email address from fileimport datetimefrom time import timeif __name__ == "__main__": start = time() hashtable = {} f = file("email.txt","r") f2 = file("email_new.txt","w") for line in f.xreadlines():
if not hashtable.has_key(line):
hashtable[line] = 1
f2.write(line) f.close() f2.close() print (time() - start) * 1000, "ms"在我的机器上执行结果如下:lijie t #
test1.py8 mslijie t #
test1.py9 mslijie t #
test1.py9 mslijie t #
test1.py4 mslijie t #
test1.py3 ms不过还是没有m网友的效率高。
在F版本的基础上,借鉴m网友的做法,实现一个G版本:G、排序并去除重复元素,比较hash和字符串版本:&!---->#include &iostream&#include &string&#include &fstream&#include &iterator&#include &sys/time.h&#include &vector&using namespacesize_t my_hash (const char* str){
size_t ret = 0;
while (*str)
ret = 11 * ret + *str++;
return}class Email{private:
const char*
friend bool operator & (const Email& lhs, const Email& rhs);public:
Email (const char* mail_)
: hash(my_hash(mail_)), mail(mail_)
bool operator == (const Email& rhs)
if (hash == rhs.hash)
return strcmp(mail, rhs.mail) == 0;
return false;
const char* getEmail()const
}};bool operator & (const Email& lhs, const Email& rhs){
if (lhs.hash == rhs.hash)
return strcmp(lhs.mail, rhs.mail) & 0;
return lhs.hash & rhs.}int main(int argc, char** argv){
if (argc & 3)
cout && "Wrong arguments" &&
FILE* fin = fopen(argv[1], "r");
cout && "Invalid input file" &&
FILE* fout = fopen(argv[2], "w");
if (!fout)
fclose(fin);
cout && "Invalid output file" &&
timeval start,
const int BUF_SIZE = 20 * 1024 * 1024;
char* buffer = new char[BUF_SIZE];
memset(buffer, 0, BUF_SIZE);
gettimeofday(&start, 0);
vector&Email&
size_t read = fread (buffer, BUF_SIZE, 1, fin);
char* begin =
char* current =
while (*current != '\0')
if (*current == '\n')
*current = '\0';
emails.push_back(begin);
begin = current + 1;
fclose(fin);
sort(emails.begin(), emails.end());
emails.erase (unique( emails.begin(), emails.end() ), emails.end());
for (vector&Email&::const_iterator iter = emails.begin();
iter != emails.end();
fputs((*iter).getEmail(), fout);
fwrite("\n", 1, 1, fout);
fclose(fout);
gettimeofday(&end, 0);
printf("Time used: %d ms\n", ((end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000));
return 0;}在我的机器上执行如下:lijie t # ./test7 email.txt email-new.txtTime used: 676 mslijie t # ./test7 email.txt email-new.txtTime used: 675 mslijie t # ./test7 email.txt email-new.txtTime used: 671 mslijie t # ./test7 email.txt email-new.txtTime used: 669 mslijie t # ./test7 email.txt email-new.txtTime used: 673 ms比F版本快了2倍,也快过了其它所有版本。不过由于数据是vector保存的,在数据大量重复的情况下,性能可能会有较大的降低。把operator&和operator==的实现改为strcmp比较,执行结果如下:lijie t # ./test8 email.txt email-new.txtTime used: 1275 mslijie t # ./test8 email.txt email-new.txtTime used: 1267 mslijie t # ./test8 email.txt email-new.txtTime used: 1297 mslijie t # ./test8 email.txt email-new.txtTime used: 1296 mslijie t # ./test8 email.txt email-new.txtTime used: 1271 ms
修改了下,增加了计时,修正了fread使用错误。&!---->#include &iostream&#include &string&#include &fstream&#include &iterator&#include &vector&using namespace#ifdef _WIN32# include &windows.h&#else // _WIN32# include &sys/time.h&#endif // _WIN32size_t my_hash (const char* str){
size_t ret = 0;
while (*str)
ret = 11 * ret + *str++;
return}class Email{private:
const char*
friend bool operator & (const Email& lhs, const Email& rhs);public:
Email (const char* mail_)
: hash(my_hash(mail_)), mail(mail_)
bool operator == (const Email& rhs)
if (hash == rhs.hash)
return strcmp(mail, rhs.mail) == 0;
return false;
const char* getEmail()const
}};bool operator & (const Email& lhs, const Email& rhs){
if (lhs.hash == rhs.hash)
return strcmp(lhs.mail, rhs.mail) & 0;
return lhs.hash & rhs.}#ifndef _WIN32class Timer{
timeval begin,public:
void start () {gettimeofday(&begin, 0);}
void stop () {gettimeofday(&end, 0);}
size_t milliseconds () const {
return (end.tv_sec - begin.tv_sec) * 1000 + (end.tv_usec - begin.tv_usec) / 1000;
}};#else // _WIN32class Timer{
DWORD begin,public:
void start () {begin = GetTickCount();}
void stop () {end = GetTickCount();}
size_t milliseconds () const {
return end -
}};#endif // _WIN32int main(int argc, char
浏览: 404641 次
来自: 上海
qiezi 写道yangyang_08 写道1 ...
yangyang_08 写道1、现在如果做并发服务器,楼主选用 ...
1、现在如果做并发服务器,楼主选用什么样的语言架构?2、lua ...
我也是语言爱好者,不过我一直坚持使用c。
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'

我要回帖

更多关于 java和python的对比 的文章

 

随机推荐