Search code examples
pythondatetimedate-conversion

Python: How do I convert time.strftime to display UTC instead of Local timezone?


I am trying to open a file whose name is changed based on UTC datetime.

I use the following to grab the filename:

datetoday = time.strftime("%Y%m%d%H%M")
print datetoday
filename = "C:\Users\Downloads\filename-%s.csv" % datetoday
inputfile = open(filename)

The issue is that this is printing the filename in local (EST) timezone and not in the UTC which I want.

Is there a way to convert time.strftime() to display UTC timezone and not local?

Thank you.


Solution

  • instead of:

    import time
    datetoday = time.strftime("%Y%m%d%H%M")
    

    try:

    from datetime import datetime
    datetoday = datetime.utcnow().strftime("%Y%m%d%H%M")