<jupyter_start><jupyter_text>Creating datetimes by handOften you create datetime objects based on outside data. Sometimes though, you want to create a datetime object from scratch.You're going to create a few different datetime objects from scratch to get the hang of that process. These come from the bikeshare data set that you'll use throughout the rest of the chapter.<jupyter_code># Import datetime
from datetime import datetime

# Create a datetime object
dt = datetime(2017, 10, 1, 15, 26, 26)

# Print the results in ISO 8601 format
print(dt.isoformat())
# Import datetime
from datetime import datetime

# Create a datetime object
dt = datetime(2017, 12, 31, 15, 19, 13)

# Print the results in ISO 8601 format
print(dt.isoformat())
# Import datetime
from datetime import datetime

# Create a datetime object
dt = datetime(2017, 12, 31, 15, 19, 13)

# Replace the year with 1917
dt_old = dt.replace(year=1917)

# Print the results in ISO 8601 format
print(dt_old)<jupyter_output>1917-12-31 15:19:13<jupyter_text>Counting events before and after noonIn this chapter, you will be working with a list of all bike trips for one Capital Bikeshare bike, W20529, from October 1, 2017 to December 31, 2017. This list has been loaded as onebike_datetimes.Each element of the list is a dictionary with two entries: start is a datetime object corresponding to the start of a trip (when a bike is removed from the dock) and end is a datetime object corresponding to the end of a trip (when a bike is put back into a dock).You can use this data set to understand better how this bike was used. Did more trips start before noon or after noon?<jupyter_code>import pandas as pd

captial_onebike = pd.read_csv('../datasets/capital-onebike.csv')

fmt = "%Y-%m-%d %H:%M:%S"

onebike_datetime_strings = list(zip(captial_onebike['Start date'], captial_onebike['End date']))

onebike_datetimes = []

# Loop over all trips
for (start, end) in onebike_datetime_strings:
  trip = {'start': datetime.strptime(start, fmt),
          'end': datetime.strptime(end, fmt)}
  
  # Append the trip
  onebike_datetimes.append(trip)
    
# Create dictionary to hold results
trip_counts = {'AM': 0, 'PM': 0}
  
# Loop over all trips
for trip in onebike_datetimes:
    # Check to see if the trip starts before noon
    if trip['start'].hour < 12:
        # Increment the counter for before noon
        trip_counts['AM'] += 1
    else:
        # Increment the counter for after noon
        trip_counts['PM'] += 1
print(trip_counts)<jupyter_output>{'AM': 94, 'PM': 196}<jupyter_text>Turning strings into datetimesWhen you download data from the Internet, dates and times usually come to you as strings. Often the first step is to turn those strings into datetime objects.In this exercise, you will practice this transformation.| Reference |    ||-----------|----||%Y|4 digit year (0000-9999)||%m|2 digit month (1-12)||%d|2 digit day (1-31)||%H|2 digit hour (0-23)||%M|2 digit minute (0-59)||%S|2 digit second (0-59)<jupyter_code># Import the datetime class
from datetime import datetime

# Starting string, in YYYY-MM-DD HH:MM:SS format
s = '2017-02-03 00:00:01'

# Write a format string to parse s
fmt = '%Y-%m-%d %H:%M:%S'

# Create a datetime object d
d = datetime.strptime(s, fmt)

# Print d
print(d)
# Import the datetime class
from datetime import datetime

# Starting string, in YYYY-MM-DD format
s = '2030-10-15'

# Write a format string to parse s
fmt = '%Y-%m-%d'

# Create a datetime object d
d = datetime.strptime(s, fmt)

# Print d
print(d)
# Import the datetime class
from datetime import datetime

# Starting string, in MM/DD/YYYY HH:MM:SS format
s = '12/15/1986 08:00:00'

# Write a format string to parse s
fmt = '%m/%d/%Y %H:%M:%S'

# Create a datetime object d
d = datetime.strptime(s, fmt)

# Print d
print(d)<jupyter_output>1986-12-15 08:00:00<jupyter_text>Parsing pairs of strings as datetimesUp until now, you've been working with a pre-processed list of datetimes for W20529's trips. For this exercise, you're going to go one step back in the data cleaning pipeline and work with the strings that the data started as.Explore onebike_datetime_strings in the IPython shell to determine the correct format. datetime has already been loaded for you.| Reference |    ||-----------|----||%Y|4 digit year (0000-9999)||%m|2 digit month (1-12)||%d|2 digit day (1-31)||%H|2 digit hour (0-23)||%M|2 digit minute (0-59)||%S|2 digit second (0-59)<jupyter_code>import pandas as pd

captial_onebike = pd.read_csv('../datasets/capital-onebike.csv')

captial_onebike
# Write down the format string
fmt = "%Y-%m-%d %H:%M:%S"

# Initialize a list for holding the pairs of datetime objects
onebike_datetimes = []

onebike_datetime_strings = list(zip(captial_onebike['Start date'], captial_onebike['End date']))

# Loop over all trips
for (start, end) in onebike_datetime_strings:
  trip = {'start': datetime.strptime(start, fmt),
          'end': datetime.strptime(end, fmt)}
  
  # Append the trip
  onebike_datetimes.append(trip)
    
onebike_datetimes<jupyter_output><empty_output><jupyter_text>Recreating ISO format with strftime()In the last chapter, you used strftime() to create strings from date objects. Now that you know about datetime objects, let's practice doing something similar.Re-create the .isoformat() method, using .strftime(), and print the first trip start in our data set.<jupyter_code># Import datetime
from datetime import datetime

# Pull out the start of the first trip
first_start = onebike_datetimes[0]['start']

# Format to feed to strftime()
fmt = "%Y-%m-%dT%H:%M:%S"

# Print out date with .isoformat(), then with .strftime() to compare
print(first_start.isoformat())
print(first_start.strftime(fmt))<jupyter_output>2017-10-01T15:23:25
2017-10-01T15:23:25<jupyter_text>Unix timestampsDatetimes are sometimes stored as Unix timestamps: the number of seconds since January 1, 1970. This is especially common with computer infrastructure, like the log files that websites keep when they get visitors.<jupyter_code># Import datetime
from datetime import datetime

# Starting timestamps
timestamps = [1514665153, 1514664543]

# Datetime objects
dts = []

# Loop
for ts in timestamps:
  dts.append(datetime.fromtimestamp(ts))
  
# Print results
print(dts)<jupyter_output>[datetime.datetime(2017, 12, 31, 3, 19, 13), datetime.datetime(2017, 12, 31, 3, 9, 3)]<jupyter_text>Turning pairs of datetimes into durationsWhen working with timestamps, we often want to know how much time has elapsed between events. Thankfully, we can use datetime arithmetic to ask Python to do the heavy lifting for us so we don't need to worry about day, month, or year boundaries. Let's calculate the number of seconds that the bike was out of the dock for each trip.Continuing our work from a previous coding exercise, the bike trip data has been loaded as the list onebike_datetimes. Each element of the list consists of two datetime objects, corresponding to the start and end of a trip, respectively.<jupyter_code># Initialize a list for all the trip durations
onebike_durations = []

for trip in onebike_datetimes:
    # Create a timedelta object corresponding to the length of the trip
    trip_duration = trip['end'] - trip['start']
  
    # Get the total elapsed seconds in trip_duration
    trip_length_seconds = trip_duration.total_seconds()
  
    # Append the results to our list
    onebike_durations.append(trip_length_seconds)
    
onebike_durations<jupyter_output><empty_output><jupyter_text>Average trip timeW20529 took 291 trips in our data set. How long were the trips on average? We can use the built-in Python functions sum() and len() to make this calculation.Based on your last coding exercise, the data has been loaded as onebike_durations. Each entry is a number of seconds that the bike was out of the dock.<jupyter_code># What was the total duration of all trips?
total_elapsed_time = sum(onebike_durations)

# What was the total number of trips?
number_of_trips = len(onebike_durations)
  
# Divide the total duration by the number of trips
print(total_elapsed_time / number_of_trips)<jupyter_output>1178.9310344827586<jupyter_text>The long and the short of why time is hardOut of 291 trips taken by W20529, how long was the longest? How short was the shortest? Does anything look fishy?As before, data has been loaded as onebike_durations.<jupyter_code># Calculate shortest and longest trips
shortest_trip = min(onebike_durations)
longest_trip = max(onebike_durations)

# Print out the results
print("The shortest trip was " + str(shortest_trip) + " seconds")
print("The longest trip was " + str(longest_trip) + " seconds")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09064665127020785, 'fraction_numerical': 0.03764434180138568, 'mean_word_length': 4.731965585704831, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '487253', 'license': 'MIT', 'n_tokens_mistral': 2936, 'n_tokens_neox': 2635, 'n_words': 1079, 'path': 'working-with-dates-and-times-in-python/2. Combining Dates and Times/notebook_section_2.ipynb', 'repo_name': 'nhutnamhcmus/datacamp-playground', 'size': '8660'}