机器学习大数据 爬虫Python AI SqlPython 运维

Python日期时间模块简单示例

2017-09-29  本文已影响20人  Jiafu

不多说,python中用到日期、时间的话使用datetime这个模块,下面给出一些简单的用法示例,包括创建实例、格式化、由字符串创建实例、简单计算等等。

Python代码:

# -*- coding: utf8 -*-

from datetime import datetime

#get current datetime

datetime_now = datetime.now()

print "now:", datetime_now

 
#create two datetime object

datetime1 = datetime(year = 2012, month = 2, day = 28)

datetime2 = datetime(year = 2012, month = 2, day = 29, hour = 12, minute = 30, second = 30, microsecond = 1000)

print "datetime1:", datetime1, " datetime2:", datetime2

 
#format

##%a    Locale’s abbreviated weekday name.     
##%A    Locale’s full weekday name.     
##%b    Locale’s abbreviated month name.     
##%B    Locale’s full month name.     
##%c    Locale’s appropriate date and time representation.     
##%d    Day of the month as a decimal number [01,31].     
##%H    Hour (24-hour clock) as a decimal number [00,23].     
##%I    Hour (12-hour clock) as a decimal number [01,12].     
##%j    Day of the year as a decimal number [001,366].     
##%m    Month as a decimal number [01,12].     
##%M    Minute as a decimal number [00,59].     
##%p    Locale’s equivalent of either AM or PM.    (1)

##%S    Second as a decimal number [00,61].    (2)

##%U    Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)

##%w    Weekday as a decimal number [0(Sunday),6].     
##%W    Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)

##%x    Locale’s appropriate date representation.     
##%X    Locale’s appropriate time representation.     
##%y    Year without century as a decimal number [00,99].     
##%Y    Year with century as a decimal number.     
##%Z    Time zone name (no characters if no time zone exists).     
##%%    A literal '%' character.

print datetime1.strftime("%d/%m/%y")

print datetime2.strftime("%A %d. %B %Y")

 
#strptime

str_time = "Sat Mar 28 22:24:24 2009"

b = datetime.strptime(str_time, "%a %b %d %H:%M:%S %Y")

print b

 
#calculate

delta_T =  datetime2 - datetime1

print "delta_T:", delta_T, ";delta_T.seconds:", delta_T.seconds, ";delta_T.total_seconds():", delta_T.total_seconds()

print datetime1 < datetime2

输出:

now: 2012-02-29 10:42:34.625000
datetime1: 2012-02-28 00:00:00 datetime2: 2012-02-29 12:30:30.001000
28/02/12
Wednesday 29. February 2012
2009-03-28 22:24:24
delta_T: 1 day, 12:30:30.001000 ;delta_T.seconds: 45030 ;delta_T.total_seconds(): 131430.001
True

上一篇 下一篇

猜你喜欢

热点阅读