---
title: "Python日常"
author: "rainbow_小春"
date: "2017-10-25T14:10:00Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2017-10-25T19:09:10Z"
id: 2397578
url: "https://719607746.iteye.com/blog/2397578"
---

1、

同一个流好像还不能读俩遍，必须关了重来

 

2、

源数据后面有（\\r\\n）于是我之前写的strip('\\r').strip('\\n')

然并卵！造吗

number=line.split('\\t')

.strip('\\n').strip('\\r')才能去掉后面的\\r

读取时报错x44x23keyfailed(错误大意，并没有记录准确)

 

3、

try:passprintdict\[line\[0].strip('\\n').strip('\\r')]exceptException:printline\[0].strip()

 

4、

strip（）只能去空格/t…需strip（'/n'）strip('/r')去⋯⋯\\r\\n同时出现我也是跪了\_(:3」∠)\_看是否因为这个，需直接printdict

![抓狂](http://static.blog.csdn.net/xheditor/xheditor_emot/default/crazy.gif)

否则这辈子也发现不了哪的问题(O\_O)。。

 

5、

ifdict.has\_key(line2\[0])==False:dict\[line2\[0]]=line2

 

6、

记录：Python这个小婊砸只认自己创的表哒，以前创的表要删掉再执行，如果不想报错的话

![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)

，“”要换成''

![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)

，往Oracle导的话，hive可以不建，Oracle必须建。还有,Python只认vi

 

7、Python获取当前日期的前一天

计算前一天

&gt;&gt;&gt; import datetime  
&gt;&gt;&gt; datetime.datetime.now() - datetime.timedelta(days=1)

 

计算一周前某天

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

`importdatetime`

 

`#今天`

`today=datetime.datetime.today()`

`printtoday`

 

`#一周前的今天`

`aWeekDelta=datetime.timedelta(weeks=1)`

`aWeekAgo=today-aWeekDelta`

`printaWeekAgo`

 

`#格式式的一周前的今天`

`formated='%d&%d&%d&%d&%d&%d'%(aWeekAgo.year,aWeekAgo.month,aWeekAgo.day,\`

`aWeekAgo.hour,aWeekAgo.minute,aWeekAgo.second)`

`printformated`

` `

` `

` `

` `

`下一个方法`

`datetime.datetime.fromtimestamp(time.time()-7*24*3600).strftime("%Y&%m&%d&%H &%I&%S")`

from datetime import *

import datetime

 

yesterday = date.today() + datetime.timedelta(-1) //前一天

yyyy-mm-dd格式

 

time可以进行自定义格式化

import time  
nom = time.time()  
n = 1  
before = now - n * 24 * 3600#可以改变n 的值计算n天前的

date = time.strftime("%Y%m%d",time.localtime(now))  
beforeDate = time.strftime("%Y%m%d",time.localtime(before))

print date  
print beforeDate

转换时间戳

def transtime(timestamp):

return time.strftime('%Y%m%d-%H',time.localtime(timestamp))

#return time.strptime(timestamp, "%Y%m%d-%H")

 

最常用的time.time()返回的是一个浮点数，单位为秒。但strftime处理的类型是time.struct\_time，实际上是一个tuple。strptime和localtime都会返回这个类型。

&gt;&gt;&gt; import time  
&gt;&gt;&gt; t = time.time()  
&gt;&gt;&gt; t  
1202872416.4920001  
&gt;&gt;&gt; type(t)  
&lt;type 'float'&gt;  
&gt;&gt;&gt; t = time.localtime()  
&gt;&gt;&gt; t  
(2008, 2, 13, 10, 56, 44, 2, 44, 0)  
&gt;&gt;&gt; type(t)  
&lt;type 'time.struct\_time'&gt;  
&gt;&gt;&gt; time.strftime('%Y-%m-%d', t)  
'2008-02-13'  
&gt;&gt;&gt; time.strptime('2008-02-14', '%Y-%m-%d')  
(2008, 2, 14, 0, 0, 0, 3, 45, -1)