[关闭]
@Channelchan 2018-09-29T22:37:55.000000Z 字数 2154 阅读 78004

datetime

操作日期和时间的package

1、 主要介绍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: 用于表示时区的抽象类

2、 datetime()参数

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

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

打印特定时间

  1. import warnings
  2. warnings.filterwarnings('ignore')
  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.now())
2018-09-12 17:38:41.024984

返回当前UTC时间

  1. print(datetime.utcnow())
2018-09-12 09:38:41.031977

从1970年1月1日0时开始所经历的秒数的当地时间

  1. print(datetime.fromtimestamp(1000000000))
2001-09-09 09:46:40

3、 格式转换 format

  1. # 通过给定的format将date_string转换成datetime
  2. print(type(datetime.strptime("2017-01-01 01:02:03.000007", "%Y-%m-%d %H:%M:%S.%f")))
<class 'datetime.datetime'>
  1. # 通过给定的format将datetime类型转换成string
  2. print(datetime.now().strftime(format="%Y%m%d %H:%M:%S.%f"))
20180912 17:38:41.054953

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

4、 迭代转换时间格式

  1. import pandas as pd
  2. from datetime import timedelta
  3. 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

5、 timedelta()

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

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

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

6、 timedelta与datetime做简单的四则运算

  1. now = datetime.now()
  2. td = timedelta(1)
  3. print (now)
  4. print (td)
  5. print (now + td * 2)
2018-09-12 17:39:11.506369
1 day, 0:00:00
2018-09-14 17:39:11.506369
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注