Search code examples
pythondatetimetimestamptype-conversionstrftime

How to convert strftime or string format to timestamp/Date in python?


I am very new to Python coding. I was trying to get the start and end date of a month and then compare it with another date column in the same excel.

I only need the date in mm/dd/yy format but do not need the time. The final_month_end_date is basically a string format which I compare with an actual date but it gives me an error saying

"TypeError: Cannot compare type 'Timestamp' with type 'str'"

I have also tried .timestamp() function but of no use. How can I resolve this problem?

import datetime as dt
import strftime

now1 = dt.datetime.now()
current_month= now1.month
current_year= now1.year
month_start_date= dt.datetime.today().strftime("%Y/%m/01")
month_end_date= calendar.monthrange(current_year,current_month)[1]
final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)

Solution

  • To convert a string to a DateTime object use datetime.strptime. Once you have the datetime object, convert it to a unix timestamp using time.mktime.

    import time
    import datetime as dt
    from time import mktime
    from datetime import datetime
    
    now1 = dt.datetime.now()
    current_month= now1.month
    current_year= now1.year
    month_start_date= dt.datetime.today().strftime("%Y/%m/01")
    month_end_date= "30"
    final_month_end_date= dt.datetime.today().strftime("%Y/%m/"+month_end_date)
    
    # Use datetime.strptime to convert from string to datetime
    month_start = datetime.strptime(month_start_date, "%Y/%m/%d")
    month_end = datetime.strptime(final_month_end_date, "%Y/%m/%d")
    
    # Use time.mktime to convert datetime to timestamp
    timestamp_start = time.mktime(month_start.timetuple())
    timestamp_end = time.mktime(month_end.timetuple())
    
    # Let's print the time stamps
    print "Start timestamp: {0}".format(timestamp_start)
    print "End timestamp: {0}".format(timestamp_end)