Date and Time in Python

 In Python, you can work with dates and times using the `datetime` module, which provides classes for manipulating dates and times. Below are some common operations and examples:


1. **Get Current Date and Time**


You can get the current date and time using the `datetime` class:


```python

from datetime import datetime


# Get current date and time

now = datetime.now()

print("Current Date and Time:", now)

```


 2. **Format Date and Time**


You can format the date and time using the `strftime` method:


```python

formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")

print("Formatted Date and Time:", formatted_date)

```


Common format codes:

- `%Y`: Year (e.g., 2023)

- `%m`: Month (01 to 12)

- `%d`: Day (01 to 31)

- `%H`: Hour (00 to 23)

- `%M`: Minute (00 to 59)

- `%S`: Second (00 to 59)

 3. **Get Individual Components**


You can extract individual components like year, month, day, hour, minute, and second:


```python

year = now.year

month = now.month

day = now.day

hour = now.hour

minute = now.minute

second = now.second


print(f"Year: {year}, Month: {month}, Day: {day}")

print(f"Hour: {hour}, Minute: {minute}, Second: {second}")

```

 4. **Create a Specific Date**


You can create a specific date using the `datetime` class:


```python

from datetime import datetime


specific_date = datetime(2023, 10, 25, 15, 30, 0)

print("Specific Date and Time:", specific_date)

```


5. **Calculate Difference Between Dates**


You can calculate the difference between two dates using the `timedelta` class:


```python

from datetime import datetime, timedelta


date1 = datetime(2023, 10, 25)

date2 = datetime(2023, 11, 1)


difference = date2 - date1

print("Difference in Days:", difference.days)

```

 6. **Add or Subtract Time**


You can add or subtract time using the `timedelta` class:


```python

from datetime import datetime, timedelta


now = datetime.now()

future_date = now + timedelta(days=10)

past_date = now - timedelta(hours=5)


print("Current Date and Time:", now)

print("Future Date (10 days later):", future_date)

print("Past Date (5 hours earlier):", past_date)

```


7. **Convert String to Date**


You can convert a string to a `datetime` object using the `strptime` method:


```python

date_string = "2023-10-25 15:30:00"

date_object = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")

print("Date Object:", date_object)

```


 8. **Timezone-Aware Date and Time**


For timezone-aware operations, you can use the `pytz` library or Python's built-in `timezone` class:


```python

from datetime import datetime

from pytz import timezone


# Get current time in a specific timezone

tz = timezone('US/Eastern')

now = datetime.now(tz)

print("Current Date and Time in US/Eastern:", now)

```


 9. **Unix Timestamp**


You can convert a `datetime` object to a Unix timestamp and vice versa:


```python

# Convert datetime to Unix timestamp

timestamp = datetime.timestamp(now)

print("Unix Timestamp:", timestamp)


# Convert Unix timestamp to datetime

date_from_timestamp = datetime.fromtimestamp(timestamp)

print("Date from Timestamp:", date_from_timestamp)

```


10. **Sleep for a Specific Duration**


You can pause the execution of your program for a specific duration using the `time` module:


```python

import time


print("Start")

time.sleep(5)  # Sleep for 5 seconds

print("End")

```


These are some of the basic operations you can perform with dates and times in Python. The `datetime` module is very powerful and provides many more functionalities for handling dates and times.

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Wear OS Android UI Application in Kotlin

Kotlin Android Program (QCR) Application Codes That Read Text in Photos