首页 > 代码库 > python datetime模块的日常使用

python datetime模块的日常使用

python datetime模块的日常使用


[10:52:43][root@sam| ~]# python

Python 2.7.12 (default, Jun 27 2017, 11:19:01)

[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> import datetime

# 获得当前时间,以字符串格式输出

>>> datetime.datetime.now()    # 输出当前时间,datetime格式

datetime.datetime(2017, 7, 31, 10, 53, 8, 430324)

>>> print type(datetime.datetime.now())

<type ‘datetime.datetime‘>

>>> datetime.datetime.now().strftime("%F %T")    # datetime格式转换为str格式

‘2017-07-31 10:53:46‘

>>> print type(datetime.datetime.now().strftime("%F %T"))

<type ‘str‘>

# 计算时间差

>>> start = datetime.datetime.now()

>>> end = datetime.datetime.now()

>>> print start, type(start)

2017-07-31 10:58:36.875319 <type ‘datetime.datetime‘>

>>> print end, type(end)

2017-07-31 10:58:51.778787 <type ‘datetime.datetime‘>

>>> time_seconds = (end - start).seconds    # 相差多少秒

>>> print time_seconds, type(time_seconds)

14 <type ‘int‘>

>>> time_microseconds = (end - start).microseconds    # 相差多少微秒

>>> print time_microseconds, type(time_microseconds)

903468 <type ‘int‘>

>>> time_days = (end - start).days    # 相差多少天

>>> print time_days, type(time_days)

0 <type ‘int‘>

>>> delta_time = float(str(time_days*86400 + time_seconds) + "." + str(time_microseconds))    # 计算相差多少秒(需要相加三部分)

>>> print delta_time, type(delta_time)

14.903468 <type ‘float‘>

# 将时间转换str格式到datetime格式

>>> time_string = "2012-02-02 22:22:22"

>>> print type(time_string)

<type ‘str‘>

>>> time_datetime = datetime.datetime.strptime(time_string, "%Y-%m-%d %H:%M:%S")

>>> print time_datetime, type(time_datetime)

2012-02-02 22:22:22 <type ‘datetime.datetime‘>

# 计算两个时间的时间差

>>> t1 = "2012-02-02 22:22:22"

>>> t2 = "2012-02-28 11:11:11"

>>> t1_datetime = datetime.datetime.strptime(t1, "%Y-%m-%d %H:%M:%S")

>>> t2_datetime = datetime.datetime.strptime(t2, "%Y-%m-%d %H:%M:%S")

>>> t2_datetime

datetime.datetime(2012, 2, 28, 11, 11, 11)

>>> t1_datetime

datetime.datetime(2012, 2, 2, 22, 22, 22)

>>> print (t2_datetime - t1_datetime).days

25

>>> print (t2_datetime - t1_datetime).seconds

46129

>>> delta_t = delta_days*86400 + delta_seconds    # 计算相差多少秒

>>> print delta_t, type(delta_t)

2206129 <type ‘int‘>

注意:

t2时间部分换算成秒:40271

t1时间部分换算成秒:80542

所以秒数相减的话,需要自动从天数借一天,即86400+40271-80542=46219

而天数相减就变为28-1-2=25


python datetime模块的日常使用