欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python_时间处理

程序员文章站 2022-04-06 15:54:55
...

常用命令

时间戳:timestamp

import time as tm
now=tm.time()
print now
1501475503.61

日期时间:datetime、strftime

#datetime类型
import datetime as dt
now=dt.datetime.now()
print now
2017-07-31 12:27:07.250000

print type(now)
<type 'datetime.datetime'>

#字符串类型
import datetime as dt
now=dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print now
2017-07-31 14:16:47

print type(now)
<type 'str'>

日期:date

#获取当日日期
now=dt.datetime.now().date()
print now
2017-07-31
print type(now)
<type 'datetime.date'>
#或者
now=dt.date.today()

#获取昨日日期
def getYesterday():  
  today=datetime.date.today() 
  oneday=datetime.timedelta(days=1) 
  yesterday=today-oneday  
  return yesterday 

转换

datetime-string

datetime -> string

>>> import datetime as dt
>>> dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2017-07-31 14:27:08'

string -> datetime

>>> import datetime as dt
>>> dt.datetime.strptime("2017-07-31 18:20:10", "%Y-%m-%d %H:%M:%S")
2017-07-31 18:20:10

datetime-timestamp

datetime -> timestamp

>>> now = dt.datetime.now()
>>> timestamp = time.mktime(now.timetuple())
>>> timestamp
1501476642.57

timestamp -> datetime

>>> dt.datetime.fromtimestamp(1501476642.57)
2017-07-31 12:50:42.570000

博文参考:http://blog.csdn.net/yl2isoft/article/details/52077991