<返回更多

15个例子,掌握Python日期时间处理

2022-01-07    程序汪小成
加入收藏

日常工作中,用 Python/ target=_blank class=infotextkey>Python 处理时间格式的数据是非常常见的,今天就来分享 DateTime 相关的示例。

1使用 time 模块展示当前日期和时间

import time
from time import gmtime, strftime
 
t = time.localtime()
print (time.asctime(t))
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))
print(strftime("%A", gmtime()))
print(strftime("%D", gmtime()))
print(strftime("%B", gmtime()))
print(strftime("%y", gmtime()))
 
# Convert seconds into GMT date
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))

Output:

Sun May 7 09:30:37 2017
Sun, 07 May 2017 04:00:37 +0000
Sunday
05/07/17
May
17
Fri, 13 Feb 2009 23:31:30 +0000

2将天、小时、分钟转换为秒

SECONDS_PER_MINUTE  = 60
SECONDS_PER_HOUR    = 3600
SECONDS_PER_DAY     = 86400
 
#Read the inputs from user
days    = int(input("Enter number of Days: "))
hours   = int(input("Enter number of Hours: "))
minutes = int(input("Enter number of Minutes: "))
seconds = int(input("Enter number of Seconds: "))
 
#Calculate the days, hours, minutes and seconds
total_seconds = days * SECONDS_PER_DAY
total_seconds = total_seconds + ( hours * SECONDS_PER_HOUR)
total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE)
total_seconds = total_seconds + seconds
 
#Display the result
print("Total number of seconds: ","%d"%(total_seconds))

Output:

Enter number of Days: 5
Enter number of Hours: 36
Enter number of Minutes: 24
Enter number of Seconds: 15
Total number of seconds: 563055

3使用 Pandas 获取当前日期和时间

import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)

Output:

2018-01-19 16:08:28.393553
2018-01-19
2018
1
19
16
8
28
394553

4将字符串转换为日期时间对象

from datetime import datetime
from dateutil import parser

d1 = "Jan 7 2015  1:15PM"
d2 = "2015 Jan 7  1:33PM"

# If you know date format
date1 = datetime.strptime(d1, '%b %d %Y %I:%M%p')
print(type(date1))
print(date1)

# If you don't know date format
date2 = parser.parse(d2)
print(type(date2))
print(date2)

Output:

class 'datetime.datetime'
2015-01-07 13:15:00

class 'datetime.datetime'
2015-01-07 13:33:00

5以毫秒为单位获取当前时间

import time
 
milliseconds = int(round(time.time() * 1000))
print(milliseconds)

Output:

1516364270650

6以 MST、EST、UTC、GMT 和 HST 获取当前日期时间

from datetime import datetime
from pytz import timezone
 
mst = timezone('MST')
print("Time in MST:", datetime.now(mst))
 
est = timezone('EST')
print("Time in EST:", datetime.now(est))
 
utc = timezone('UTC')
print("Time in UTC:", datetime.now(utc))
 
gmt = timezone('GMT')
print("Time in GMT:", datetime.now(gmt))
 
hst = timezone('HST')
print("Time in HST:", datetime.now(hst))

Output:

Time in MST: 2017-01-19 06:06:14.495605-07:00
Time in EST: 2017-01-19 08:06:14.496606-05:00
Time in UTC: 2017-01-19 13:06:14.496606+00:00
Time in GMT: 2017-01-19 13:06:14.496606+00:00
Time in HST: 2017-01-19 03:06:14.497606-10:00

7从给定的日期当中获取星期几

import datetime
 
dayofweek = datetime.date(2010, 6, 16).strftime("%A")
print(dayofweek)
# weekday Monday is 0 and Sunday is 6
print("weekday():", datetime.date(2010, 6, 16).weekday())
 
# isoweekday() Monday is 1 and Sunday is 7
print("isoweekday()", datetime.date(2010, 6, 16).isoweekday())
 
dayofweek = datetime.datetime.today().strftime("%A")
print(dayofweek)
print("weekday():", datetime.datetime.today().weekday())
print("isoweekday()", datetime.datetime.today().isoweekday())

Output:

Wednesday
weekday(): 2
isoweekday() 3
Friday
weekday(): 4
isoweekday() 5

8计算两个日期时间对象之间的时差

import datetime
from datetime import timedelta
 
datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
date1 = '2016-04-16 10:01:28.585'
date2 = '2016-03-10 09:56:28.067'
diff = datetime.datetime.strptime(date1, datetimeFormat)
    - datetime.datetime.strptime(date2, datetimeFormat)
 
print("Difference:", diff)
print("Days:", diff.days)
print("Microseconds:", diff.microseconds)
print("Seconds:", diff.seconds)

Output:

Difference: 37 days, 0:05:00.518000
Days: 37
Microseconds: 518000
Seconds: 300

9将 5 分钟添加到 Unix 时间戳

import datetime
import calendar
 
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
print(calendar.timegm(future.timetuple()))

Output:

1621069619

10在 Python 中遍历一系列日期

import datetime

start = datetime.datetime.strptime("21-06-2020", "%d-%m-%Y")
end = datetime.datetime.strptime("05-07-2020", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days)]

for date in date_generated:
    print(date.strftime("%d-%m-%Y"))

Output:

21-06-2020
22-06-2020
23-06-2020
24-06-2020
25-06-2020
26-06-2020
27-06-2020
28-06-2020
29-06-2020
30-06-2020
01-07-2020
02-07-2020
03-07-2020
04-07-2020

11巴黎时间更改为纽约时间

import pendulum
 
in_paris = pendulum.datetime(2016, 8, 7, 22, 24, 30, tz='Europe/Paris')
print(in_paris)
 
in_us = in_paris.in_timezone('America/New_York')
print(in_us)

Output:

2016-08-07T22:24:30+02:00
2016-08-07T16:24:30-04:00

12使用 Python 获得最后7个工作日

from datetime import date
from datetime import timedelta
 
today = date.today()
 
for i in range(7):
    d = today - timedelta(days=i)
    if d.weekday() < 5:
        print(d)

Output:

2021-05-18
2021-05-17
2021-05-14
2021-05-13
2021-05-12

13从今天的日期和一个人的生日推算年龄

from datetime import date
 
 
def calculate_age(born):
    today = date.today()
    try:
        birthday = born.replace(year=today.year)
    except ValueError:
        birthday = born.replace(year=today.year, month=born.month + 1, day=1)
    if birthday > today:
        return today.year - born.year - 1
    else:
        return today.year - born.year
 
 
print(calculate_age(date(2001, 3, 1)))

Output:

20

14获得本月的第一个星期二

import calendar
from datetime import datetime
 
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
monthcal = c.monthdatescalendar(datetime.today().year, datetime.today().month)
 
try:
    tues = [day for week in monthcal for day in week if
            day.weekday() == calendar.TUESDAY and day.month == datetime.today().month][0]
    print(tues)
except IndexError:
    print('No date found')

Output:

2021-05-04

15将整数转换为日期对象

from datetime import datetime

i = 1545730073
timestamp = datetime.fromtimestamp(i)

print(timestamp)
print(type(timestamp))

Output:

2018-12-25 14:57:53
声明:本站部分内容来自互联网,如有版权侵犯或其他问题请与我们联系,我们将立即删除或处理。
▍相关推荐
更多资讯 >>>