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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mitsuhide1992

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值