2

I am trying to write a function that will convert a string date/time from local time to UTC in Python.

According to this question, you can use time.tzname to get some forms of the local timezone, but I have not found a way to use this in any of the datetime conversion methods. For example, this article shows there are a couple of things you can do with pytz and datetime to convert times, but all of them have timezones that are hardcoded in and are of different formats than what time.tznamereturns.

Currently I have the following code to translate a string-formatted time into milliseconds (Unix epoch):

local_time = time.strptime(datetime_str, "%m/%d/%Y %H:%M:%S") # expects UTC, but I want this to be local
dt = datetime.datetime(*local_time[:6])
ms = int((dt - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000)

However, this is expecting the time to be input as UTC. Is there a way to convert the string formatted time as if it were in the local timezone? Thanks.

Essentially, I want to be able to do what this answer does, but instead of hard-coding in "America/Los_Angeles", I want to be able to dynamically specify the local timezone.

Community
  • 1
  • 1
Logan
  • 1,575
  • 1
  • 17
  • 26
  • from time import gmtime, strftime LocTime = strftime("%a, %d %b %Y %H:%M:%S") GMTime = strftime("%Y %m %d T %H:%M:%S (GMT)", gmtime()) print "Local :",LocTime print "UTC :",GMTime – Mr. zero Jun 30 '16 at 00:16
  • you want to convert from local time 2 utc ? – Mr. zero Jun 30 '16 at 00:17
  • you can get timezone with : tz = strftime("%Z") – Mr. zero Jun 30 '16 at 00:23
  • @Mr.zero Yes, I want to convert from local time to utc. Yes, I can also get that with time.tzname, but how can I use that to do a conversion from that timezone that it returns to UTC? For example, maybe using pytz's astimezone() method. – Logan Jun 30 '16 at 00:27
  • @Mr.zero I also want to be able to pass any time I want, not just using 'now'. Thanks for your help. – Logan Jun 30 '16 at 00:37

2 Answers2

2

If I understand your question correctly you want this :

from time import strftime,gmtime,mktime,strptime

# you can pass any time you want
strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(strptime("Thu, 30 Jun 2016 03:12:40", "%a, %d %b %Y %H:%M:%S"))))

# and here for real time
strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(strptime(strftime("%a, %d %b %Y %H:%M:%S"), "%a, %d %b %Y %H:%M:%S"))))
Mr. zero
  • 245
  • 4
  • 18
0

make a time structure from a timetuple then use the structure to create a utc time

from datetime import datetime

def local_to_utc(local_st):
    time_struct = time.mktime(local_st)
    utc_st = datetime.utcfromtimestamp(time_struct)
    return utc_st

d=datetime(2016,6,30,3,12,40,0)
timeTuple = d.timetuple()
print(local_to_utc(timeTuple))

output:

2016-06-30 09:12:40
Golden Lion
  • 3,840
  • 2
  • 26
  • 35