Pin-Jiun / Python

Python Document
0 stars 0 forks source link

10-Module datetime #10

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

datetime

Python Datetime module comes built into Python, so there is no need to install it externally

Date and datetime are an object in Python, so when you manipulate them, you are actually manipulating objects and not string or timestamps.

The DateTime module is categorized into 6 main classes –

  1. date – Its attributes are year, month and day.
  2. time – An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. Its attributes are hour, minute, second, microsecond, and tzinfo.
  3. datetime – Its a combination of date and time along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
  4. timedelta – A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
  5. tzinfo – It provides time zone information objects.
  6. timezone – A class that implements the tzinfo abstract base class as a fixed offset from the UTC (New in version 3.2).

Date class

it represents a date in the format YYYY-MM-DD. Constructor of this class needs three mandatory arguments year, month and date.

Constructor syntax:

class datetime.date(year, month, day)
# Python program to
# demonstrate date class

# import the date class
from datetime import date

# initializing constructor
# and passing arguments in the
# format year, month, date
my_date = date(1996, 12, 11)

print("Date passed as argument is", my_date)
#1996-12-11

# Uncommenting my_date = date(1996, 12, 39)
# will raise an ValueError as it is
# outside range

# uncommenting my_date = date('1996', 12, 11)
# will raise a TypeError as a string is
# passed instead of integer

Get Today’s Year, Month, and Date

from datetime import date

# date object of today's date
today = date.today()

print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

Timestamp

We can create date objects from timestamps y=using the fromtimestamp() method. The timestamp is the number of seconds from 1st January 1970 at UTC to a particular date.

from datetime import datetime

# Getting Datetime from timestamp
date_time = datetime.fromtimestamp(1887639468)
print("Datetime from timestamp:", date_time)

Convert Date to String

We can convert date object to a string representation using two functions isoformat() and strftime().

from datetime import date

# calling the today
# function of date class
today = date.today()

# Converting the date to the string
Str = date.isoformat(today)
print("String Representation", Str)
print(type(Str))

其他常見的method

Function Name | Description -- | -- ctime() | Return a string representing the date fromisocalendar() | Returns a date corresponding to the ISO calendar fromisoformat() | Returns a date object from the string representation of the date fromordinal() | Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1 fromtimestamp() | Returns a date object from the POSIX timestamp isocalendar() | Returns a tuple year, week, and weekday isoformat() | Returns the string representation of the date isoweekday() | Returns the day of the week as integer where Monday is 1 and Sunday is 7 replace() | Changes the value of the date object with the given parameter strftime() | Returns a string representation of the date with the given format timetuple() | Returns an object of type time.struct_time today() | Returns the current local date toordinal() | Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1 weekday() | Returns the day of the week as integer where Monday is 0 and Sunday is 6

參考網址 https://www.geeksforgeeks.org/python-datetime-module/

Pin-Jiun commented 1 year ago

Python DateTime – Time Class

from datetime import time

# calling the constructor
my_time = time(12, 14, 36)

print("Entered time", my_time)

# calling constructor with 1
# argument
my_time = time(minute = 12)
print("\nTime with one argument", my_time)

# Calling constructor with
# 0 argument
my_time = time()
print("\nTime without argument", my_time)

# Uncommenting time(hour = 26)
# will rase an ValueError as
# it is out of range

# uncommenting time(hour ='23')
# will raise TypeError as
# string is passed instead of int

Class Attributes

Attribute Name | Description -- | -- min | Minimum possible representation of time max | Maximum possible representation of time resolution | The minimum possible difference between time objects hour | The range of hour must be between 0 and 24 (not including 24) minute | The range of minute must be between 0 and 60 (not including 60) second | The range of second must be between 0 and 60 (not including 60) microsecond | The range of microsecond must be between 0 and 1000000 (not including 1000000) tzinfo | The object containing timezone information fold | Represents if the fold has occurred in the time or not

Getting min and max representable time

from datetime import time

# Getting min time
mintime = time.min
print("Min Time supported", mintime)

# Getting max time
maxtime = time.max
print("Max Time supported", maxtime)

Accessing the hour, minutes, seconds, and microseconds attribute from the time class

from datetime import time

# Creating Time object
Time = time(12,24,36,1212)

# Accessing Attributes
print("Hour:", Time.hour)
print("Minutes:", Time.minute)
print("Seconds:", Time.second)
print("Microseconds:", Time.microsecond)

Class Functions

<html>
<body>
<!--StartFragment-->

Function Name | Description
-- | --
dst() | Returns tzinfo.dst() is tzinfo is not None
fromisoformat() | Returns a time object from the string representation of the time
isoformat() | Returns the string representation of time from the time object
replace() | Changes the value of the time object with the given parameter
strftime() | Returns a string representation of the time with the given format
tzname() | Returns tzinfo.tzname() is tzinfo is not None
utcoffset() | Returns tzinfo.utcffsets() is tzinfo is not None

<!--EndFragment-->
</body>
</html>

Converting time object to string and vice versa

from datetime import time

# Creating Time object
Time = time(12,24,36,1212)

# Converting Time object to string
Str = Time.isoformat()
print("String Representation:", Str)
print(type(Str))

Time = "12:24:36.001212"

# Converting string to Time object
Time = time.fromisoformat(Str)
print("\nTime from String", Time)
print(type(Time))

Changing the value of an already created time object and formatting the time

from datetime import time

# Creating Time object
Time = time(12,24,36,1212)
print("Original time:", Time)

# Replacing hour
Time = Time.replace(hour = 13, second = 12)
print("New Time:", Time)

# Formatting Time
Ftime = Time.strftime("%I:%M %p")
print("Formatted time", Ftime)
Pin-Jiun commented 1 year ago

DateTime Class

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
# Python program to
# demonstrate datetime object

from datetime import datetime

# Initializing constructor
a = datetime(2022, 10, 22)
print(a)

# Initializing constructor
# with time parameters as well
a = datetime(2022, 10, 22, 6, 2, 32, 5456)
print(a)

``
___________
### Class Attributes
<html>
<body>
<!--StartFragment-->

Attribute Name | Description
-- | --
min | The minimum representable DateTime
max | The maximum representable DateTime
resolution | The minimum possible difference between datetime objects
year | The range of year must be between MINYEAR and MAXYEAR
month | The range of month must be between 1 and 12
day | The range of day must be between 1 and number of days in the given month of the given year
hour | The range of hour must be between 0 and 24 (not including 24)
minute | The range of minute must be between 0 and 60 (not including 60)
second | The range of second must be between 0 and 60 (not including 60)
microsecond | The range of microsecond must be between 0 and 1000000 (not including 1000000)
tzinfo | The object containing timezone information
fold | Represents if the fold has occurred in the time or not

<!--EndFragment-->
</body>
</html>

```python
from datetime import datetime

# Getting Today's Datetime
today = datetime.now()

# Accessing Attributes
print("Day: ", today.day)
print("Month: ", today.month)
print("Year: ", today.year)
print("Hour: ", today.hour)
print("Minute: ", today.minute)
print("Second: ", today.second)

Class Functions

Function Name | Description -- | -- astimezone() | Returns the DateTime object containing timezone information. combine() | Combines the date and time objects and return a DateTime object ctime() | Returns a string representation of date and time date() | Return the Date class object fromisoformat() | Returns a datetime object from the string representation of the date and time fromordinal() | Returns a date object from the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. The hour, minute, second, and microsecond are 0 fromtimestamp() | Return date and time from POSIX timestamp isocalendar() | Returns a tuple year, week, and weekday isoformat() | Return the string representation of date and time isoweekday() | Returns the day of the week as integer where Monday is 1 and Sunday is 7 now() | Returns current local date and time with tz parameter replace() | Changes the specific attributes of the DateTime object strftime() | Returns a string representation of the DateTime object with the given format strptime() | Returns a DateTime object corresponding to the date string time() | Return the Time class object timetuple() | Returns an object of type time.struct_time timetz() | Return the Time class object today() | Return local DateTime with tzinfo as None toordinal() | Return the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1 tzname() | Returns the name of the timezone utcfromtimestamp() | Return UTC from POSIX timestamp utcoffset() | Returns the UTC offset utcnow() | Return current UTC date and time weekday() | Returns the day of the week as integer where Monday is 0 and Sunday is 6

Converting Strings Using datetime

import datetime

date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)

Convert date, time and datetime objects to its equivalent string

from datetime import datetime

now = datetime.now() # current date and time

year = now.strftime("%Y")
print("year:", year)

month = now.strftime("%m")
print("month:", month)

day = now.strftime("%d")
print("day:", day)

time = now.strftime("%H:%M:%S")
print("time:", time)

date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)