Working with Dates and Time in Python
In this lab, you will learn how to work with dates and times in Python using the datetime
module. You can perform the exercises in any of the following environments:
- Visual Studio Code (VS Code)
- Google Colab
- Jupyter Notebook
- PyCharm
- Anaconda
Setup Instructions
1. Visual Studio Code (VS Code)
- Installation: Ensure Python is installed and the Python extension is added to VS Code.
- Create a new file: Open VS Code and create a new Python file (e.g.,
date_time_lab.py
). - Run the code: Use the editor’s terminal or run button to execute your code.
2. Google Colab
- Access Colab: Go to Google Colab.
- Create a New Notebook: Click on “New Notebook.”
- Run Cells: Write your code in a cell and run it by clicking the play button.
3. Jupyter Notebook
- Installation: Install Jupyter Notebook via Anaconda or pip.
- Start Jupyter: Open your terminal and type launch”
jupyter notebook
to launch. - Create a New Notebook: Create a new Python notebook and write your code in the cells.
4. PyCharm
- Installation: Download and install PyCharm.
- Create a New Project: Start a new project and create a new Python file.
- Run the code: Write and run your code using the built-in run configuration.
5. Anaconda
- Launch Anaconda Navigator: Open Anaconda Navigator.
- Choose an environment: Launch either Jupyter Notebook or Spyder.
- Create a New File/Notebook: Write your code in a new notebook or script.
Exercises
Exercise 1: Current Date and Time
Task:
- Import the
datetime
module. - Get the current date and time and print it.
Example Code:
import datetime
# Get current date and time
now = datetime.datetime.now()
# Print current date and time
print("Current Date and Time:", now)
Exercise 2: Formatting Dates
Task:
- Create a date object for your birthday.
- Format the date in different ways (e.g.,
YYYY-MM-DD
,DD/MM/YYYY
).
Example Code:
import datetime
# Create a date object for your birthday
birthday = datetime.date(1990, 1, 1) # Change to your birth date
# Format the date
formatted1 = birthday.strftime("%Y-%m-%d")
formatted2 = birthday.strftime("%d/%m/%Y")
# Print formatted dates
print("Birthday (YYYY-MM-DD):", formatted1)
print("Birthday (DD/MM/YYYY):", formatted2)
Exercise 3: Date Arithmetic
Task:
- Calculate the number of days until your next birthday.
- Print the result.
Example Code:
import datetime
# Create a date object for your next birthday
today = datetime.date.today()
next_birthday = datetime.date(today.year, 1, 1) # Change to your next birthday
# If the birthday already passed this year, calculate for next year
if next_birthday < today:
next_birthday = datetime.date(today.year + 1, 1, 1)
# Calculate the difference in days
days_until_birthday = (next_birthday - today).days
# Print the result
print("Days until next birthday:", days_until_birthday)
Exercise 4: Working with Time
Task:
- Get the current time.
- Format the time as
HH:MM:SS
.
Example Code:
import datetime
# Get current time
current_time = datetime.datetime.now().time()
# Format the time
formatted_time = current_time.strftime("%H:%M:%S")
# Print the formatted time
print("Current Time (HH:MM:SS):", formatted_time)
Running the Code
- Copy the Code: Copy the code examples provided above into your Python file.
- Run the program: Execute the program in your IDE. You can usually do this by clicking a “Run” button or using a keyboard shortcut (like
Shift + F10
in PyCharm). - Interact with the program: Follow the prompts in the console to input your data if applicable.
Conclusion
This lab helps you understand how to work with dates and times in Python using the datetime
module. By completing these exercises, you will gain practical experience with date formatting, arithmetic, and time manipulation. Enjoy coding!
or
Lab 04: Working with Dates and Time in Python (Civil Engineering Focus)
Objective: Learn to handle dates, times, and time-series data for construction scheduling, sensor data analysis, and project management.
Key Concepts
- Core Modules:
datetime
Basic date/time creation, formatting, and arithmetic.pandas
Time-series data handling (e.g., sensor readings over time).dateutil
Parse dates from strings (useful for unstructured data).
- Civil Engineering Applications:
- Track construction milestones.
- Analyze sensor data (e.g., bridge vibrations over days).
- Calculate concrete curing periods.
- Monitor equipment maintenance schedules.
Task 1: Concrete Curing Time Calculator
Problem:
Calculate the curing end date and time based on the concrete pour start time and curing duration (7 days).
Sample Input:
Enter pour date and time (YYYY-MM-DD HH:MM): 2023-10-05 14:30
Sample Output:
Curing Start: 2023-10-05 14:30
Curing End: 2023-10-12 14:30
Solution Code:
from datetime import datetime, timedelta
pour_time = input("Enter pour date and time (YYYY-MM-DD HH:MM): ")
start = datetime.strptime(pour_time, "%Y-%m-%d %H:%M")
curing_duration = timedelta(days=7)
end = start + curing_duration
print(f"\nCuring Start: {start.strftime('%Y-%m-%d %H:%M')}")
print(f"Curing End: {end.strftime('%Y-%m-%d %H:%M')}")
Task 2: Construction Schedule Tracker
Problem:
Determine if a project is ahead/behind schedule by comparing planned vs. actual milestone dates.
Sample Input:
Planned completion date (YYYY-MM-DD): 2023-11-15
Actual completion date (YYYY-MM-DD): 2023-11-20
Sample Output:
Planned: 2023-11-15
Actual: 2023-11-20
Delay: 5 days
Solution Code:
from datetime import datetime
planned = datetime.strptime(input("Planned completion date (YYYY-MM-DD): "), "%Y-%m-%d")
actual = datetime.strptime(input("Actual completion date (YYYY-MM-DD): "), "%Y-%m-%d")
delta = (actual - planned).days
status = "Ahead" if delta < 0 else "Behind" if delta > 0 else "On Time"
print(f"\nPlanned: {planned.date()}\nActual: {actual.date()}")
print(f"Delay: {abs(delta)} days ({status})")
Task 3: Sensor Data Time-Series Analysis
Problem:
Analyze a CSV file (bridge_vibrations.csv
) containing timestamps and vibration amplitudes. Calculate the maximum amplitude per day.
CSV Example:
timestamp,amplitude(mm)
2023-10-01 08:00:00,5.2
2023-10-01 12:30:00,7.1
2023-10-02 09:15:00,12.3
Sample Output:
2023-10-01: 7.10 mm
2023-10-02: 12.30 mm
Solution Code:
import pandas as pd
# Load data and parse timestamps
df = pd.read_csv('bridge_vibrations.csv', parse_dates=['timestamp'])
df['date'] = df['timestamp'].dt.date # Extract date part
# Group by date and find max amplitude
daily_max = df.groupby('date')['amplitude(mm)'].max()
print("Maximum Daily Vibrations:")
for date, amplitude in daily_max.items():
print(f"{date}: {amplitude:.2f} mm")
Task 4: Equipment Maintenance Reminder
Problem:
Generate maintenance reminders for construction equipment based on last service dates (every 90 days).
Sample Input File (equipment.csv
):
equipment_id,last_service_date
E101,2023-01-15
E102,2023-03-20
Sample Output:
E101: Last serviced on 2023-01-15. Next due by 2023-04-14!
E102: Last serviced on 2023-03-20. Next due by 2023-06-18!
Solution Code:
import pandas as pd
from datetime import timedelta
df = pd.read_csv('equipment.csv', parse_dates=['last_service_date'])
today = pd.to_datetime('today')
for _, row in df.iterrows():
next_service = row['last_service_date'] + timedelta(days=90)
due_in = (next_service - today).days
print(f"{row['equipment_id']}: Last serviced on {row['last_service_date'].date()}. Next due by {next_service.date()} ({due_in} days remaining)")
Key Takeaways
- Date Arithmetic: Calculate deadlines, durations, and delays using.
timedelta
- Parsing Dates: Convert strings to
datetime
objects for analysis. - Time-Series Grouping: Aggregate sensor or project data by day/week/month.
- Real-World Workflows: Automate maintenance schedules and compliance checks.
Challenge Problem
Problem:
A weather API returns timestamps in UNIX format (e.g., 1696281600
= 2023-10-02 12:00:00 UTC). Write a program to:
- Convert UNIX timestamps to readable dates.
- Flag days with > 50 mm rainfall (to predict construction delays).
Sample API Data:
{"timestamp": 1696281600, "rainfall": 60}
{"timestamp": 1696368000, "rainfall": 45}
Solution Snippet:
import pandas as pd
from datetime import datetime
data = [
{"timestamp": 1696281600, "rainfall": 60},
{"timestamp": 1696368000, "rainfall": 45}
]
df = pd.DataFrame(data)
df['date'] = df['timestamp'].apply(lambda x: datetime.utcfromtimestamp(x).strftime('%Y-%m-%d'))
high_rain_days = df[df['rainfall'] > 50]['date'].tolist()
print(f"Days with heavy rain: {high_rain_days}")