字元串操作 1.字元串的翻轉 # 方式一 s = 'hello world' print(s[::-1) # 方式二 from functools import reduce print(reduce(lambda x,y:y+x, s)) 2.判斷字元串是否是迴文 利用字元串翻轉操作可以查看字元串 ...
一、使用 time 模塊展示當前日期和時間
import time
from time import gmtime, strftime
t = time.localtime()
print (time.asctime(t)) # Sun May 7 09:30:37 2017
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())) # Sun, 07 May 2017 04:00:37 +0000
print(strftime("%A", gmtime())) # Sunday
print(strftime("%D", gmtime())) # 05/07/17
print(strftime("%B", gmtime())) # May
print(strftime("%y", gmtime())) # 17
# Convert seconds into GMT date
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890))) # Fri, 13 Feb 2009 23:31:30 +0000
二、將天、小時、分鐘轉換為秒
SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = 3600
SECONDS_PER_DAY = 86400
# 輸入天、小時、分鐘、秒的數量
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: "))
# 計算
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
# 結果
print("Total number of seconds: ","%d"%(total_seconds))
'''
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
'''
三、使用 Pandas 獲取當前日期和時間
import pandas as pd
print(pd.datetime.now()) # 2018-01-19 16:08:28.393553
print(pd.datetime.now().date()) # 2018-01-19
print(pd.datetime.now().year) # 2018
print(pd.datetime.now().month) # 1
print(pd.datetime.now().day) # 19
print(pd.datetime.now().hour) # 16
print(pd.datetime.now().minute) # 8
print(pd.datetime.now().second) # 28
print(pd.datetime.now().microsecond) # 394553
四、將字元串轉換為日期時間對象
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)) # class 'datetime.datetime'
print(date1) # 2015-01-07 13:15:00
# If you don't know date format
date2 = parser.parse(d2)
print(type(date2)) # class 'datetime.datetime'
print(date2) # 2015-01-07 13:33:00
五、以毫秒為單位獲取當前時間
import time
milliseconds = int(round(time.time() * 1000))
print(milliseconds) # 1516364270650
六、以 MST、EST、UTC、GMT 和 HST 獲取當前日期時間
from datetime import datetime
from pytz import timezone
mst = timezone('MST')
print("Time in MST:", datetime.now(mst)) # Time in MST: 2017-01-19 06:06:14.495605-07:00
est = timezone('EST')
print("Time in EST:", datetime.now(est)) # Time in EST: 2017-01-19 08:06:14.496606-05:00
utc = timezone('UTC')
print("Time in UTC:", datetime.now(utc)) # Time in UTC: 2017-01-19 13:06:14.496606+00:00
gmt = timezone('GMT')
print("Time in GMT:", datetime.now(gmt)) # Time in GMT: 2017-01-19 13:06:14.496606+00:00
hst = timezone('HST')
print("Time in HST:", datetime.now(hst)) # Time in HST: 2017-01-19 03:06:14.497606-10:00
七、從給定的日期當中獲取星期幾
import datetime
dayofweek = datetime.date(2010, 6, 16).strftime("%A")
print(dayofweek) # Wednesday
# weekday()方法: 0代表周一,6代表周日
print("weekday():", datetime.date(2010, 6, 16).weekday()) # weekday(): 2
# isoweekday() 方法: 1代表周一,7代表周日
print("isoweekday()", datetime.date(2010, 6, 16).isoweekday()) # isoweekday() 3
dayofweek = datetime.datetime.today().strftime("%A")
print(dayofweek) # Friday
print("weekday():", datetime.datetime.today().weekday()) # weekday(): 4
print("isoweekday()", datetime.datetime.today().isoweekday()) # isoweekday(): 5
八、計算兩個日期時間對象之間的時差
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) # Difference: 37 days, 0:05:00.518000
print("Days:", diff.days) # Days: 37
print("Microseconds:", diff.microseconds) # Microseconds: 518000
print("Seconds:", diff.seconds) # Seconds: 300
九、將 5 分鐘添加到 Unix 時間戳
import datetime
import calendar
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
print(calendar.timegm(future.timetuple())) # 1621069619
十、遍歷一系列日期
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"))
十一、巴黎時間更改為紐約時間
import pendulum
in_paris = pendulum.datetime(2016, 8, 7, 22, 24, 30, tz='Europe/Paris')
print(in_paris) # 2016-08-07T22:24:30+02:00
in_us = in_paris.in_timezone('America/New_York')
print(in_us) # 2016-08-07T16:24:30-04:00
十二、使用 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)
十三、從今天的日期和一個人的生日推算年齡
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)))
十四、獲得本月的第一個星期二
import calendar
from datetime import datetime
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
monthcal = c.monthdatescalendar(datetime.today().year, datetime.today().month)
#Python小白學習交流群:153708845
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')
十五、將整數轉換為日期對象
from datetime import datetime
i = 1545730073
timestamp = datetime.fromtimestamp(i)
print(timestamp) # 2018-12-25 14:57:53
print(type(timestamp))
十六、當前日期減去 N 天的天數
from datetime import datetime, timedelta
d = datetime.today() - timedelta(days=5)
print(d)
十七、比較兩個日期
import datetime
a = datetime.datetime(2020, 12, 31, 23, 59, 59)
b = datetime.datetime(2020, 11, 30, 23, 59, 59)
print(a < b)
print(a > b)
十八、從 datetime 對象中提取年份
import datetime
year = datetime.date.today().year
print(year)
十九、根據日期找到星期幾
import pendulum
dt = pendulum.parse('2021-05-18')
print(dt.day_of_week) # 2
dt = pendulum.parse('2021-05-01')
print(dt.day_of_week) # 6
dt = pendulum.parse('2021-05-21')
print(dt.day_of_week) # 5
二十、從當前日期獲取 7 天前的日期
from datetime import datetime, timedelta
now = datetime.now()
for x in range(7):
d = now - timedelta(days=x)
print(d.strftime("%Y-%m-%d"))
二十一、將兩個日期時間對象之間的差值轉換為秒
import datetime
time1 = datetime.datetime.strptime('19 01 2021', '%d %m %Y')
time2 = datetime.datetime.strptime('25 01 2021', '%d %m %Y')
difference = time2 - time1
print(difference) # 6 days, 0:00:00
seconds = difference.total_seconds()
print(seconds) # 518400.0
二十二、獲得任何一個月的第N個星期五
import calendar
# 取2021年5月的第三個星期五
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year = 2021
month = 5
n = 2 # 取第三個
monthcal = c.monthdatescalendar(year, month)
try:
third_friday = [
day for week in monthcal
for day in week if
day.weekday() == calendar.FRIDAY and day.month == month
][n]
print(third_friday) # 2021-05-21
except IndexError:
print('No date found')
二十三、根據周數獲取日期
import datetime
from dateutil.relativedelta import relativedelta
week = 25
year = 2021
date = datetime.date(year, 1, 1) + relativedelta(weeks=+week)
print(date) # 2021-06-25
二十四、獲取特定日期的工作日
import datetime
print(datetime.date(2020, 5, 15).isocalendar()[2]) # 5
二十五、創建一個 15 分鐘前的 DateTime
import datetime
#Python小白學習交流群:153708845
dt = datetime.datetime.now() - datetime.timedelta(minutes=15)
print(dt) # 2021-05-15 22:25:55.897365
二十六、從特定日期獲取周的開始和結束日期
import pendulum
dt = pendulum.datetime(2012, 9, 5)
start = dt.start_of('week')
print(start.to_datetime_string()) # 2012-09-03 00:00:00
end = dt.end_of('week')
print(end.to_datetime_string()) # 2012-09-09 23:59:59
二十七、兩個日期之間的差異(以秒為單位)
from datetime import datetime
#Python小白學習交流群:153708845
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2020-01-01 17:31:22', fmt)
d2 = datetime.strptime('2020-01-03 17:31:22', fmt)
days_diff = d2 - d1
print(days_diff.days * 24 * 60 * 60) # 172800
二十八、以這種格式獲取昨天的日期MMDDYY
from datetime import date, timedelta
yesterday = date.today() - timedelta(days=1)
print(yesterday.strftime('%m%d%y')) # 051421
二十九、根據今天的日期獲取上周三的日期
from datetime import date
from datetime import timedelta
today = date.today()
offset = (today.weekday() - 2) % 7
wednesday = today - timedelta(days=offset)
print(wednesday) # 2021-05-12
三十、所有可用時區的列表列印
import pytz
for i in pytz.all_timezones:
print(i)