python timestamp和datetime之间转换详解
做开发中难免时间类型之间的转换,最近就发现前端js和后端django经常要用到这个转换,其中jsDate.now()精确到毫秒,而Python中Datetime.datetime.now()是精确到微秒的。
1.字符串日期时间转换成时间戳
#'2015-08-2816:43:37.283'-->1440751417.283
#或者'2015-08-2816:43:37'-->1440751417.0
defstring2timestamp(strValue):
try:
d=datetime.datetime.strptime(strValue,"%Y-%m-%d%H:%M:%S.%f")
t=d.timetuple()
timeStamp=int(time.mktime(t))
timeStamp=float(str(timeStamp)+str("%06d"%d.microsecond))/1000000
printtimeStamp
returntimeStamp
exceptValueErrorase:
printe
d=datetime.datetime.strptime(str2,"%Y-%m-%d%H:%M:%S")
t=d.timetuple()
timeStamp=int(time.mktime(t))
timeStamp=float(str(timeStamp)+str("%06d"%d.microsecond))/1000000
printtimeStamp
returntimeStamp
2.时间戳转换成字符串日期时间
#1440751417.283-->'2015-08-2816:43:37.283'
deftimestamp2string(timeStamp):
try:
d=datetime.datetime.fromtimestamp(timeStamp)
str1=d.strftime("%Y-%m-%d%H:%M:%S.%f")
#2015-08-2816:43:37.283000'
returnstr1
exceptExceptionase:
printe
return''
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志