[原] Python日期/时间操作方法使用

Python日期/时间操作方法使用

 

0. 模块:

import os, sys

import time, datetime

1. 得到当前时间

(1) Based on time module:

import os, sys, time, datetime

startTime = time.localtime()

注意这里: startTime

<type 'time.struct_time'>

(2) Based on datetime module:

import os, sys, time, datetime

nowTime = datetime.datetime.now()

type(nowTime)
<type 'datetime.datetime'>

2. 日期转字符串:

(1) str(xx)

(2) time提供的函数:

time.strftime([format], time)

strStartTime = time.strftime('%Y-%m-%d %H:%M:%S', startTime)

'2009-06-03 13:44:51'

 

3. 字符串转日期:

(1) 字符串转time:

d = time.strptime(strStartTime, '%Y-%m-%d %H:%M:%S')

(2009, 6, 3, 13, 44, 51, 2, 154, -1)

type(d)
<type 'time.struct_time'>

(2) 字符串转datetime

datetime的好处是可以实现方便的时间运算,比如 endTime - starTime,这在时间duration计算时非常方便.

    # Convert string start time and end time to datetime.datetime
    startTime = datetime.datetime(tmpStartTime[0], tmpStartTime[1], tmpStartTime[2], tmpStartTime[3],  tmpStartTime[4], tmpStartTime[5] );

基于上面的转换.

 

 

转载于:https://www.cnblogs.com/SunWentao/archive/2009/06/03/1495325.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值