日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

日常工作中,用 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

分享到:
標簽:Python
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定