[关闭]
@Channelchan 2017-11-27T13:49:55.000000Z 字数 2142 阅读 137377

Datetime

主要介绍datetime和timedelta类型

datetime是python中用来管理和表示时间的模块,可用的类型有:

class datetime.date: 表示日期, 属性有: year, month 和 day。

class datetime.time: 表示一天内的时间, 属性有: hour, minute, second, microsecond 和 tzinfo。

class datetime.datetime: date和time合并, 属性有: year, month, day, hour, minute, second, microsecond 和 tzinfo。

class datetime.timedelta: 两个时间点(date, time, datetime)之间的一段时间

class datetime.tzinfo: 用于表示时区的抽象类

datetime()

class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

需要输入的参数有year, month和day, 其他为可选项。除tzinfo以外其他类型均为int或long。

  1. from datetime import datetime
  2. print(datetime(2017, 1, 2, 3, 4, 5, 6))
2017-01-02 03:04:05.000006
  1. print(datetime(2017, 1, 2, 3, 4, 5, 6))
2017-01-02 03:04:05.000006
  1. # 返回当前时间
  2. print(datetime.now())
2017-11-21 20:58:50.727869
  1. # 返回当前UTC时间
  2. print(datetime.utcnow())
2017-11-21 12:58:50.733870
  1. # 返回输入的timestamp(从1970年1月1日0时开始所经历的秒数)代表的当地时间
  2. print(datetime.fromtimestamp(1000000000))
2001-09-09 09:46:40
  1. # 通过给定的format将date_string转换成datetime
  2. print(datetime.strptime("2017-01-01 01:02:03.000007", "%Y-%m-%d %H:%M:%S.%f"))
2017-01-01 01:02:03.000007
  1. # 通过给定的format将datetime类型转换成string
  2. print(datetime.now().strftime(format="%Y-%m-%d %H:%M:%S.%f"))
2017-11-21 20:58:50.751875

format的格式详见:
https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

timedelta()

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

所有参数都不是必须的, 类型为int, long或float, 正负都可以。

  1. from datetime import timedelta
  2. delta=timedelta(days=1, seconds=-2,microseconds=-3, minutes=-4, hours=-5, weeks=6)
  3. print(delta.days, delta.seconds, delta.microseconds)
42 68157 999997

timedelta与datetime可以做简单的四则运算:

  1. now = datetime.now()
  2. td = timedelta(1)
  3. print (now)
  4. print (td)
  5. print (now + td * 2)
2017-11-21 20:58:50.763878
1 day, 0:00:00
2017-11-23 20:58:50.763878
  1. import pandas as pd
  2. stock = pd.read_excel('sz50.xlsx',sheetname='600036.XSHG', index_col='datetime')
  1. stock.index = list(map(lambda x: x-timedelta(hours=15), stock.index))
  1. print(stock.tail())
             close    high     low    open    volume
2017-11-14  111.81  112.81  110.57  110.93  42886800
2017-11-15  111.25  112.73  110.21  111.65  34028800
2017-11-16  112.13  112.13  109.73  110.77  33138100
2017-11-17  117.24  117.67  112.93  112.93  74014200
2017-11-20  121.82  122.50  116.20  116.92  64388900

datetime官方文档:https://docs.python.org/2/library/datetime.html

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注