python时间处理

来源:互联网 发布:男宝胶囊和知柏地黄丸 编辑:程序博客网 时间:2024/05/16 17:35

datetime -> string

>>> import datetime>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")'2015-01-12 23:13:08'

string -> datetime

>>> import datetime>>> datetime.datetime.strptime("2014-12-31 18:20:10", "%Y-%m-%d %H:%M:%S")datetime.datetime(2014, 12, 31, 18, 20, 10)

时间加减

是对datetime的数据处理,string类型要先转换
使用timedelta加减

import datetimestartDay = datetime.datetime.strptime("%s" % day, "%Y-%m-%d")endDay = startDay + datetime.timedelta(days=1)startDay = startDay.strftime("%Y-%m-%d")endDay = endDay.strftime("%Y-%m-%d")timeStamp = datetime.datetime.strptime("%s 00:00:00" % startDay, "%Y-%m-%d %H:%M:%S")endStamp = datetime.datetime.strptime("%s 00:00:00" % endDay, "%Y-%m-%d %H:%M:%S")timeStamp = timeStamp + datetime.timedelta(minutes=5)

计算时间差

秒和microseconds微秒10^-6

end = round(time.time()*1000)  print end  end_ = datetime.utcnow()  print end_  c = (end_ - start_)  print c.seconds    print c.microseconds   print c.total_seconds() 

millisecond毫秒10^-3 python不支持
c.seconds,只适用于一天内的时间差,如果超过一天需要使用c.total_seconds(),见python官方文档:
https://docs.python.org/2/library/datetime.html?highlight=timedelta#datetime.timedelta

A timedelta object represents a duration, the difference between two dates or times.class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative.Only days, seconds and microseconds are stored internally. Arguments are converted to those units:A millisecond is converted to 1000 microseconds.A minute is converted to 60 seconds.An hour is converted to 3600 seconds.A week is converted to 7 days.and days, seconds and microseconds are then normalized so that the representation is unique, with0 <= microseconds < 10000000 <= seconds < 3600*24 (the number of seconds in one day)-999999999 <= days <= 999999999If any argument is a float and there are fractional microseconds, the fractional microseconds left over from all arguments are combined and their sum is rounded to the nearest microsecond. If no argument is a float, the conversion and normalization processes are exact (no information is lost).If the normalized value of days lies outside the indicated range, OverflowError is raised.
0 0
原创粉丝点击