Movatterモバイル変換


[0]ホーム

URL:


Menu
×
Sign In
+1 Get Certified For Teachers Spaces Plus Get Certified For Teachers Spaces Plus
   ❮     
     ❯   

Python Tutorial

Python HOMEPython IntroPython Get StartedPython SyntaxPython CommentsPython VariablesPython Data TypesPython NumbersPython CastingPython StringsPython BooleansPython OperatorsPython ListsPython TuplesPython SetsPython DictionariesPython If...ElsePython MatchPython While LoopsPython For LoopsPython FunctionsPython LambdaPython ArraysPython Classes/ObjectsPython InheritancePython IteratorsPython PolymorphismPython ScopePython ModulesPython DatesPython MathPython JSONPython RegExPython PIPPython Try...ExceptPython String FormattingPython User InputPython VirtualEnv

File Handling

Python File HandlingPython Read FilesPython Write/Create FilesPython Delete Files

Python Modules

NumPy TutorialPandas TutorialSciPy TutorialDjango Tutorial

Python Matplotlib

Matplotlib IntroMatplotlib Get StartedMatplotlib PyplotMatplotlib PlottingMatplotlib MarkersMatplotlib LineMatplotlib LabelsMatplotlib GridMatplotlib SubplotMatplotlib ScatterMatplotlib BarsMatplotlib HistogramsMatplotlib Pie Charts

Machine Learning

Getting StartedMean Median ModeStandard DeviationPercentileData DistributionNormal Data DistributionScatter PlotLinear RegressionPolynomial RegressionMultiple RegressionScaleTrain/TestDecision TreeConfusion MatrixHierarchical ClusteringLogistic RegressionGrid SearchCategorical DataK-meansBootstrap AggregationCross ValidationAUC - ROC CurveK-nearest neighbors

Python DSA

Python DSALists and ArraysStacksQueuesLinked ListsHash TablesTreesBinary TreesBinary Search TreesAVL TreesGraphsLinear SearchBinary SearchBubble SortSelection SortInsertion SortQuick SortCounting SortRadix SortMerge Sort

Python MySQL

MySQL Get StartedMySQL Create DatabaseMySQL Create TableMySQL InsertMySQL SelectMySQL WhereMySQL Order ByMySQL DeleteMySQL Drop TableMySQL UpdateMySQL LimitMySQL Join

Python MongoDB

MongoDB Get StartedMongoDB Create DBMongoDB CollectionMongoDB InsertMongoDB FindMongoDB QueryMongoDB SortMongoDB DeleteMongoDB Drop CollectionMongoDB UpdateMongoDB Limit

Python Reference

Python OverviewPython Built-in FunctionsPython String MethodsPython List MethodsPython Dictionary MethodsPython Tuple MethodsPython Set MethodsPython File MethodsPython KeywordsPython ExceptionsPython Glossary

Module Reference

Random ModuleRequests ModuleStatistics ModuleMath ModulecMath Module

Python How To

Remove List DuplicatesReverse a StringAdd Two Numbers

Python Examples

Python ExamplesPython CompilerPython ExercisesPython QuizPython ServerPython SyllabusPython Study PlanPython Interview Q&APython BootcampPython CertificatePython Training

PythonDatetime


Python Dates

A date in Python is not a data type of its own, but we can import a module nameddatetime to work with dates as date objects.

Example

Import the datetime module and display the current date:

import datetime

x = datetime.datetime.now()
print(x)
Try it Yourself »

Date Output

When we execute the code from the example above the result will be:

The date contains year, month, day, hour, minute, second, and microsecond.

Thedatetime module has many methods to return information about the date object.

Here are a few examples, you will learn more about them later in this chapter:

Example

Return the year and name of weekday:

import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))
Try it Yourself »

Creating Date Objects

To create a date, we can use thedatetime() class (constructor) of thedatetime module.

Thedatetime() class requires three parameters to create a date: year, month, day.

Example

Create a date object:

import datetime

x = datetime.datetime(2020, 5, 17)

print(x)
Try it Yourself »

Thedatetime() class also takes parameters for time and timezone (hour, minute, second, microsecond, tzone), but they are optional, and has a default value of0, (None for timezone).



The strftime() Method

Thedatetime object has a method for formatting date objects into readable strings.

The method is calledstrftime(), and takes one parameter,format, to specify the format of the returned string:

Example

Display the name of the month:

import datetime

x = datetime.datetime(2018, 6, 1)

print(x.strftime("%B"))
Try it Yourself »

A reference of all the legal format codes:

DirectiveDescriptionExampleTry it
%aWeekday, short versionWedTry it »
%AWeekday, full versionWednesdayTry it »
%wWeekday as a number 0-6, 0 is Sunday3Try it »
%dDay of month 01-3131Try it »
%bMonth name, short versionDecTry it »
%BMonth name, full versionDecemberTry it »
%mMonth as a number 01-1212Try it »
%yYear, short version, without century18Try it »
%YYear, full version2018Try it »
%HHour 00-2317Try it »
%IHour 00-1205Try it »
%pAM/PMPMTry it »
%MMinute 00-5941Try it »
%SSecond 00-5908Try it »
%fMicrosecond 000000-999999548513Try it »
%zUTC offset+0100
%ZTimezoneCST
%jDay number of year 001-366365Try it »
%UWeek number of year, Sunday as the first day of week, 00-5352Try it »
%WWeek number of year, Monday as the first day of week, 00-5352Try it »
%cLocal version of date and timeMon Dec 31 17:41:00 2018Try it »
%CCentury20Try it »
%xLocal version of date12/31/18Try it »
%XLocal version of time17:41:00Try it »
%%A % character%Try it »
%GISO 8601 year2018Try it »
%uISO 8601 weekday (1-7)1Try it »
%VISO 8601 weeknumber (01-53)01Try it »


 
Track your progress - it's free!
 

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp