python时间处理
Posted mitsuhide1992
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python时间处理相关的知识,希望对你有一定的参考价值。
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 datetime
startDay = 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, with
0 <= microseconds < 1000000
0 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999
If 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.
以上是关于python时间处理的主要内容,如果未能解决你的问题,请参考以下文章