半路出家,立地为猿

一个半路出家 程序猿 的一点学习点滴。。。

Python datetime模块使用

Python的time 模块功能有限,计算日期的加减的时还是用datetime比较方便

首先 import datetime
当然也可以
from datetime import datetime
from datetime import timedelta
的方式引入

以下代码均是在linux python 命令行输入显示:
一、string转datetime

str = ‘2012-11-19’

date_time = datetime.datetime.strptime(str,’%Y-%m-%d’)

date_time

datetime.datetime(2012,11,19,0,0)

二、datetime转string

date_time.strftime(‘%Y-%m-%d’)

‘2012-11-19’

三、时间的加减
1 . 计算date_time的后一天

date_time + datetime.timedelta(days=1)
datetime.datetime(2012, 11, 20, 0, 0)

2 . 计算date_time的前一天

date_time + datetime.timedelta(days=-1)
datetime.datetime(2012, 11, 18, 0, 0)

3 .计算date_time 的前一个小时

date_time + datetime.timedelta(hours=1)
datetime.datetime(2012, 11, 19, 1, 0)

本来以为timedelta 还可以直接计算 months和 years的,却发现报错:

>>> date_time + datetime.timedelta(months=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'months' is an invalid keyword argument for this function

https://docs.python.org/2/library/datetime.html 看了下:
发现只支持:
days
seconds
microseconds
milliseconds
minutes
hours
weeks

class datetime.timedelta([days[, seconds[, microseconds[,
[, minutes[, hours[, weeks]]]]]]]) All arguments are
optional and default to 0. Arguments may be ints, longs, or floats,
and may be positive or negative.

Only days, seconds and microseconds are stored internally. Arguments
are converted to those units:

A millisecond is converted to 1000 microseconds. A minute is converted
to 60 seconds. An hour is converted to 3600 seconds. A week is
converted to 7 days.

https://docs.python.org/2/library/datetime.html

阅读更多
个人分类: Python
上一篇Linux 中括号 双中括号 的区别
下一篇mysql ibdata1文件清理
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭