Đây thực sự là một vấn đề tôi đang phải đối mặt và đây là cách tôi tiếp cận nó, mục đích chính của tôi là đến ngày phân tách
class InputRequest:
"This class contain all inputs function that will be required in this program. "
def __init__[self, stockTickerName = 'YHOO', stockSite='yahoo', startDate = None,
endDate = datetime.date.today[]]:
def requestInput[self, requestType ='']:
"Fro requesting input from user"
self.__requestInput = input[requestType]
return self.__requestInput
def dateFormat[self, dateType='']:
'''
this function handles user date input
this repeats until the correct format is supplied
dataType: this is the type of date, eg: DOF, Date of Arriveal, etc
'''
while True:
try:
dateString = InputRequest.requestInput[self,dateType]
dtFormat = ['%Y/%m/%d','%Y-%m-%d','%Y.%m.%d','%Y,%m,%d','%Y\%m\%d'] #you can add extra formats needed
for i in dtFormat:
try:
return datetime.datetime.strptime[dateString, i].strftime[i]
except ValueError:
pass
except ValueError:
pass
print['\nNo valid date format found. Try again:']
print["Date must be seperated by either [/ - , . \] [eg: 2012/12/31 --> ]: "]
Chúng tôi sẽ bắt đầu với ví dụ cơ bản để trích xuất ngày và giờ hiện tại.
Python cung cấp một mô -đun DateTime, có một lớp DateTime và nó có một phương thức bây giờ []datetime, which has a class datetime and it has a method now[]
Từ DateTime Nhập DateTime
Để có thời gian ngày hiện tại bằng cách sử dụng ngay bây giờ []:
# to get current date and time
dateTimeObj = datetime.now[]
print[dateTimeObj]Output:
2019-12-29 00:57:34.108728
Trích xuất các yếu tố khác nhau của đối tượng thời gian ngày:
print[f"day: {dateTimeObj.day}, month:{dateTimeObj.month},\
year:{dateTimeObj.year} hour:{dateTimeObj.hour}, \
minute:{dateTimeObj.minute}, second:{dateTimeObj.second}"]Output:
day: 29, month:12,year:2019 hour:0, minute:41, second:4
Trích xuất ngày hiện tại chỉ giả sử chúng tôi không muốn có dấu thời gian hiện tại hoàn chỉnh, chúng tôi chỉ quan tâm đến ngày hiện tại.
Suppose we don’t want complete current timestamp, we are just interested in current date.
dateObj = datetime.now[].date[]
print[dateObj]
Output:
2019-12-29
Trích xuất thời gian hiện tại chỉ có chúng tôi chỉ muốn thời gian hiện tại, tức là không bao gồm phần ngày
Suppose we want current time only , i.e exclude date part
timeObj = datetime.now[].time[]
print[timeObj]
Output:
00:52:02.925910
Chuyển đổi đối tượng DateTime thành Chuỗi: Chúng ta cần sử dụng Strftime [DateTime,] để chuyển đổi đối tượng DateTime thành Chuỗi
We need to use strftime[datetime, ] to convert datetime object to string
datetime_str = dateTimeObj.strftime["%B %d, %Y %A, %H:%M:%S"]
print[datetime_str]Output:
'December 29, 2019 Sunday, 00:57:34'
Chuyển đổi chuỗi thành Đối tượng DateTime: Chúng ta cần sử dụng Strptime [Date_String,] để chuyển đổi một chuỗi thành đối tượng thời gian
We need to use strptime[date_string, ] to convert a string to date time object
datetime_str = '28/12/2019 22:35:56'
datetime_obj = datetime.strptime[datetime_str, '%d/%m/%Y %H:%M:%S']
print[datetime_obj]Output:
2019-12-28 22:35:56
Chuỗi cho đến ngày:
date_str = '2019-12-28'
dateObj = datetime.strptime[date_str, '%Y-%m-%d'].date[]
print[dateObj]Output:
2019-12-28
Chuỗi theo thời gian:
time_str = '13:55:26'
timeObj = datetime.strptime[time_str, '%H:%M:%S'].time[]
print[timeObj]Output:
13:55:26
Python Ngày/Thời gian Định dạng Chỉ thị%A: Ngày trong tuần là tên viết tắt địa phương. Sun, Mon%A: Ngày trong tuần là tên đầy đủ của địa phương.Sunday, Thứ Hai, Cấm%W: Ngày trong tuần là một số thập phân, trong đó 0 là Chủ nhật và 6 là Thứ Bảy.%D: Ngày của tháng dưới dạng số thập phân số không. %B: Tháng dưới dạng tên viết tắt của Locale. Jan, tháng 2%B: Tháng dưới dạng tên đầy đủ của địa phương. Tháng 1%M: Tháng dưới dạng số thập phân số không. Số thập phân bằng không. Thứ hai dưới dạng số thập phân bằng không. : Tên múi giờ [chuỗi trống nếu đối tượng ngây thơ].%J: Ngày trong năm dưới dạng số thập phân số không.%U: Số tuần của năm [Chủ nhật là ngày đầu tiên của tuần] Số thập phân đệm. Tất cả các ngày trong một năm mới trước Chủ nhật đầu tiên được coi là trong tuần 0.%W: Số tuần của năm [thứ Hai là ngày đầu tiên của tuần] là số thập phân. Tất cả các ngày trong một ngày mới Năm trước ngày thứ Hai đầu tiên được coi là trong tuần 0.%C: appr của địa phương Đại diện ngày và thời gian.
%a: Weekday as locale’s abbreviated name. sun , mon
%A : Weekday as locale’s full name.Sunday, Monday, …
%w: Weekday as a decimal number, where 0 is Sunday and 6
is Saturday.
%d: Day of the month as a zero-padded decimal number.
%b: Month as locale’s abbreviated name. Jan, Feb
%B: Month as locale’s full name. January
%m: Month as a zero-padded decimal number.
%y: Year without century as a zero-padded decimal number.
%Y: Year with century as a decimal number.
%H: Hour [24-hour clock] as a zero-padded decimal number.
%I: Hour [12-hour clock] as a zero-padded decimal number.
%p: Locale’s equivalent of either AM or PM.
%M:
Minute as a zero-padded decimal number.
%S: Second as a zero-padded decimal number.
%f: Microsecond as a decimal number, zero-padded on the left.
%z: UTC offset in the form ±HHMM[SS] [empty string if the object is naive].
%Z: Time zone name [empty string if the object is naive].
%j: Day of the year as a zero-padded decimal number.
%U: Week number of the year [Sunday as the first day of the week] as a zero padded decimal number.
All days in a new year preceding the first
Sunday are considered to be in week 0.
%W: Week number of the year [Monday as the first day of the week] as a decimal number.
All days in a new year preceding the first Monday are considered to be in week 0.
%c: Locale’s appropriate date and time representation.
%x: Locale’s appropriate date representation.
%X: Locale’s appropriate time representation.
%%: A literal ‘%’ character.