Data Science Explorer

[Basic Grammar] Datetime 본문

Python

[Basic Grammar] Datetime

grace21110 2023. 11. 23. 18:57
반응형
  • Python Dates 

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

 

Example 

Import the datetime module and display the current date.

import dateime 

x = datetime.datetime.now()
print(x)

 

  • Date Output 

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

2023-11-23 12:42:21.743477

which contained year, month, day, hour, minute, second and microsecond. And you might not want it all. 

 

So when you want certain outputs.

import datetime

x = datetime.datetime.now()

print(x.year)
print(x.strftime("%A"))

 

  • Creating Date Objects 

To create a date, we can use the datetime() class of the datetime module. 

The datetime() class requires three parameters to create a date. 

import datetime

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

print(x)
  • The strfttime() Method 

The datetime object has a method for formatting date objects into readable strings. It is called strftime() and takes one parameter, format, to specify the format of the returned string.

import datetime

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

print(x.strftime("%B"))

'Python' 카테고리의 다른 글

[Exercise] Functions  (0) 2024.04.05
[Basic Grammar] Python Math  (2) 2023.11.24
[Basic Grammar] Modules  (1) 2023.11.22
[Basic Grammar] Python Inheritance  (0) 2023.11.21
[Basic Grammar] Python Classes/Objects  (1) 2023.11.19