Python之时间格式处理

发布时间:2021-12-03 公开文章

I am not a designer nor a coder. I'm just a guy with a point-of-view and a computer.

 

筑基<融合<元婴<分神<渡劫<大乘

 

 

from datetime import *
#计算当前日期到国庆节还有几天?
td = date.today()
print(td)
fatherDay = date(td.year, 10, 1)
result = fatherDay - td
print('到国庆节还有', result)
print('到国庆节还有{:4d}天'.format(result.days))
2019-08-28
到国庆节还有 34 days, 0:00:00
到国庆节还有  34
#计算工作年薪
from datetime import date, timedelta
tody = date.today() #今天日期
#到职日期
work = date(2008, 7, 1)
diff = tody - work
#输出工作天数
print('工作天数:{:,}天'.format(diff.days))
result = diff/timedelta(days = 365)
print('{0:.2f}年'.format(result))
工作天数:4,075
11.16
'''
   使用datetime类别   
'''
from datetime import datetime, date, time

#datetime()构造函数 -- 参数只有年、月、日
print('Date:', datetime(2019, 2, 14))

#datetime()构造函数 -- 参数有:年、月、日, 指定时
print('Date 2:', datetime(2019, 2, 14, hour = 10))

#datetime()构造函数 -- 参数:年、月、日时、分、秒
print('Date 3:', datetime(2019, 2, 14, 10, 35, 47))

print('', datetime.strptime(
    '2019-2-14 10:35:47', '%Y-%m-%d %H:%M:%S'))
Date: 2019-02-14 00:00:00
Date 2: 2019-02-14 10:00:00
Date 3: 2019-02-14 10:35:47
 2019-02-14 10:35:47
'''
   datetime类
'''
from datetime import datetime, date, time

#获取当前的日期和时间
now = datetime.now()

#获取年、月、日属性, 以元组对象返回
print('日期:{}年{}月{}日'.format(now.year, now.month, now.day))

#获取时、分、秒属性
print('时间:{}时{}分{}秒'.format(now.hour, now.minute, now.second))
日期:2019828
时间:21294
'''
   datetime 计算两个日期差异的天数
'''
from datetime import datetime, date, time
d1 = datetime.today()
d2 = datetime(2019, 2, 14)
dr = d2 - d1
print(dr.days, '天')
-196 
'''
   将时间和日期两个对象用combine()方法组合在一起
'''
from datetime import datetime, date, time
dt = date(2015, 5, 12)    #时间,取自date()构造函数
tm = time(12, 50)         #日期,取自time()构造函数

print('日期一:', datetime.combine(dt, tm))

print('日期二:', datetime.combine(dt, tm).strftime(
    '%Y-%m-%d %h:%M:%S'))
日期一: 2015-05-12 12:50:00
日期二: 2015-05-12 May:50:00
'''
   利用timedelta构造函数可以将时间进行转换
'''
from datetime import datetime, timedelta
d1 = timedelta(days = 3, hours = 6)
d2 = timedelta(hours = 3.2)
dr = d1 + d2


print(dr.days, '天')
print('9.2时 = ', dr.seconds, '秒')
print('3天9.2时 = ', dr.total_seconds(), '秒')
3 
9.2 =  33120 
39.2 =  292320.0 
from datetime import datetime, timedelta

#创建存储星期的list对象
weeklst = ['Monday', 'Tuesday', 'Wednesday',
         'Thusday', 'Friday', 'Saturday', 'Sunday']

def getWeeks(wkName, beginDay = None):

    #如果未传入beginDay之日期,就以今天为主
    if beginDay is None:
        beginDay = datetime.today()
    #weekday()方法返回获取星期的索引值,Monday索引值为0
    indexNum = beginDay.weekday()
    target = weeklst.index(wkName)
    lastWeek = ( 7 + indexNum - target) % 7

    if lastWeek == 0:
        lastWeek = 7
    #timedelta()构造函数获取天数
    lastWeek_Day = beginDay - timedelta(
        days = lastWeek)
    return lastWeek_Day.strftime('%Y-%m-%d')

#只传入一个参数
print('按今天计算的上周二:', getWeeks('Tuesday'))

#传入二个参数
dt = datetime(2019, 3, 15)
print('按2019/3/15 计算的上周六:', getWeeks('Saturday', dt))
按今天计算的上周二: 2019-08-27
2019/3/15 计算的上周六: 2019-03-09