Python datetime 모듈 의 사용 예시

3340 단어 Pythondatetime모듈
1.현재 년 월 일 시 분 초 획득

# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print("now:{}".format(now))
year = now.year
print("year:{}".format(year))
month = now.month
print("month:{}".format(month))
day = now.day
print("day:{}".format(day))
hour = now.hour
print("hour:{}".format(hour))
minute = now.minute
print("minute:{}".format(minute))
second = now.second
print("second:{}".format(second))

2,datetime string 으로 전환

# -*- encoding=utf-8 -*-
import datetime
now = datetime.datetime.now()
print('type:{}'.format(type(now)))
print('now datetime:{}'.format(now))
now_string = now.strftime('%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(now_string)))
print('now string:{}'.format(now_string))

3.string 이 datetime 으로 전환

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:51:26'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('type:{}'.format(type(time_date)))
print(time_date)

4.시간 더하기

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('    :\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=1, hours=2, minutes=3, seconds=4)
add_end = time_date + add_info
print('  1 2   3  4  :\t{}'.format(add_end))

 5.시간 감소
① 두 시간 차

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('    :\t{}'.format(time_date))
time_str = '2021-05-29 12:12:12'
time_date2 = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('    2:\t{}'.format(time_date2))
time_date3 = time_date2 - time_date
print('   :{}'.format(time_date3))

② 하루 2 시간 3 분 4 초 빼 기(마이너스)

# -*- encoding=utf-8 -*-
import datetime
time_str = '2021-01-28 10:00:00'
time_date = datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
print('    :\t\t\t\t{}'.format(time_date))
add_info = datetime.timedelta(days=-1, hours=-2, minutes=-3, seconds=-4)
add_end = time_date + add_info
print('  1 2   3  4  :\t{}'.format(add_end))

이상 은 Python datetime 모듈 의 사용 예제 에 대한 상세 한 내용 입 니 다.Python datetime 모듈 에 관 한 자 료 는 다른 관련 글 을 주목 하 십시오!

좋은 웹페이지 즐겨찾기