关闭

Python datetime模块使用

标签: pythondatetimetimedelta
537人阅读 评论(0) 收藏 举报
分类:

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:131340次
    • 积分:1817
    • 等级:
    • 排名:千里之外
    • 原创:84篇
    • 转载:24篇
    • 译文:1篇
    • 评论:5条
    最新评论