Search code examples
pythonstrptimestrftime

Converting time format with strftime and strptime


I have a csv file contains three column. First is the date in the format of 1/3/2018. Second is time 10:00:00 AM. Third is the temperature. Now I want to use strftime() to convert the datetime object to the format "YYYY/MM/DD HH:MM:SS AM" and store a list of time that the temperature is over 80.

import csv
from datetime import datetime

with open("temp.csv") as csvfile, open('output.csv','w') as output_file: #types of file opened "wb": binary file
    csv_reader = csv.reader(csvfile, delimiter=",")
    csv_output = csv.writer(output_file)
    next(csv_reader, None) #skip header
    rows = [row for row in csv_reader if row[2] >= '80.0'] #if condition
    output = []
    for row in rows:
        date = datetime.strptime(row[0], '%m/%d/%Y') # strp is a function under datetime. convert a string to a datetime object
        time = datetime.strptime(row[1], '%H:%M:%S %p')
        output.append([date, time])
        date_str = date.strftime('%m/%d/%Y') #strftime: convert datetime object into a string
        time_str = time.strftime('%H:%M:%S %p')
        csv_output.writerow([date_str,time_str])

print(output)

The current result is:

[[datetime.datetime(2018, 1, 2, 0, 0), datetime.datetime(1900, 1, 1, 5, 0)], [datetime.datetime(2018, 1, 2, 0, 0)...

I expect the result to be:

[1/2/2018 10:00:00 ], [1/2/2018 11:00:00]....

Solution

  • import datetime
    a = '1/3/2018'
    b = '1:14:12 AM'
    in_time = datetime.datetime.strptime(b, "%I:%M:%S %p").time()
    print(in_time)
    c = datetime.datetime.combine(datetime.datetime.strptime(a, "%d/%m/%Y"), in_time)
    print(c.strftime("%d/%m/%Y %I:%M:%S %p"))
    

    Try This:

    Repl Link