Converting strings to datetime while changing timezone - python

I have many strings of dates and times (or both), like these:
'Thu Jun 18 19:30:21 2015'
'21:07:52'
I want to convert these times to the proper datetime format while also changing the timezone to UTC. The current timezone is 4 hours behind UTC. Is there a way that I can tell python to add 4 hours while converting the formats? Can it also take care of the date in UTC such that when the hour goes past 24 the date changes and time resets?
I will ultimately be inserting these into a mysql table into fields with the 'datetime' and 'time' data type, but they all need to be in UTC.

I would approach this with time.strptime() to parse the source time string, time.mktime() to convert the resulting time vector into an epoch time (seconds since 1970-01-01 00:00:00), and time.strftime() to format the time as you like.
For the timezone adjustment, you could add 4*3600 to the epoch time value or, more generally, append a timezone string to the source and use %Z to parse it.

Related

Converting from local time to UTC time in Python Pandas dataframe?

How would I efficiently convert local times in a dataframe to UTC times? There are 3 columns with information: the date (string), the timezone code (string), and the hour of the day (integer).
date
timezone
hour
7/31/2010 0:00:00
EST
1
6/14/2010 0:00:00
PST
3
6/14/2010 0:00:00
PST
4
5/30/2010 0:00:00
EDT
23
5/30/2010 0:00:00
EDT
24
After the data is converted I will be aggregating it to monthly data.
Gday.
Working with dates is described reasonably well in this answer here: converting utc to est time in python
In that case they have the timezone offsets as numbers e.g +11:00. You have the US short code. So you could convert that column to the numerical equivalent first and then use that function.
Personally I find the notation "Australia/Melbourne" way easier to deal with - especially because it thinks about daylight savings etc for you. Timezones are a nightmare. Thats described here: Python: datetime tzinfo time zone names documentation
In terms of the hour column, you can just use a string function to join those two values together to form a date and time string.
So I'd suggest you convert that timezone column to that format (I.e EST as America/New York), etc, then feed all three columns into a datetime convert line per the first answer

How to get utc time from time string in python?

In my application, i have two select options. one is for hour selection and another for minute selection. So when i fetch select option values i get values as time string like '12:34'. and I want to convert that time string to UTC time.
So, Can anyone please suggest me that how to get UTC time from timestring?
Thank you.
You don't have enough information to do that because you need to know the offset of your timezone from UTC.
But to get you started
from datetime import datetime, timedelta
offset = -2 # I live in Central European Summer Time, so I am 2 hours east of UTC
myutctime = datetime.strptime(timestring,'%H:%M') + timedelta(hours=offset)

Convert Cocoa timestamp in Python

I have a Cocoa timestamp (zero time of January 1st, 2001 00:00:00 UTC) that I need to convert in Python. When I use the following code it assumes a Unix timestamp input. Besides adding 31 years in seconds (Just under a billion seconds...) what's the best way to convert the time?
import datetime
print(datetime.datetime.fromtimestamp(int("495759456")).strftime('%Y-%m-%d %H:%M:%S'))
The output for this line of code is '1985-09-16 16:12:03'
Would something like this work for you:
from datetime import datetime
unix = datetime(1970, 1, 1) # UTC
cocoa = datetime(2001, 1, 1) # UTC
delta = cocoa - unix # timedelta instance
timestamp = datetime.fromtimestamp(int("495759456")) + delta
print(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
I didn't specify timezone information for the two starts of time as they're in the same zone so I assume it shouldn't matter which is used when computing the difference. For converting the timestamp string, you may need to adjust for your timezone if it's different than the one in which the string was generated.
The above code produces 2016-09-16 15:57:36
One thing to be careful on when doing the conversion with the above solution, is to make sure that the Cocoa timestamp's unit is the same as the one you'd want in the unix timestamp. I've noticed that at many instance the cocoa timestamp is stored in nano seconds.
Unless you want your Unix timestamp to also be represented as nano seconds, make sure to do divide the cocoa timestamp by the appropriate number before conversion. e.g. Divide by 1000000000 to convert nano seconds to seconds etc...
Source

Python - convert naive datetime to UTC

I have date that I get in specific timezone time, but system deals with it as UTC and later it converts it back in that timezone, messing time.
For example like this:
I get this time: 2014-05-05 10:50:30. its datetime object. It has no timezone info, but I can get timezone info from user that uses that time. The thing is this time is showed as 'Europe/Vilnius' time, but system deals with it as UTC and when it outputs time to user it adds +3 hours showing wrong time. It does not matter if I change timezone to users timezone on that datetime object, it still outputs with +3 hours.
For example (snippet of code):
from datetime import datetime
import pytz
create_date = datetime.strptime(stage_log.create_date, "%Y-%m-%d %H:%M:%S")
tz = pytz.timezone(self.user_id.tz)
create_date = create_date.replace(tzinfo=pytz.utc)
This does not do anything and I still get wrong time.
Is there a way to move time to be correct UTC time(so then system correctly convert to users timezone) like this:
2014-05-05 10:50:30 -> convert to UTC. If timezone is 'Europe/Vilnius', it should convert that time to 2014-05-05 07:50:30. Then when system automatically does conversions it would correctly display 2014-05-05 10:50:30, because thats the time it should display.
Also if there is a way to just get number of hours that given timezone differs from UTC, then I could just do as simple as that:
create_date.replace(hour=create_date.hour-timezone_difference)
While this question does not specifically reference odoo, hopefully the following may help others:
Odoo - convert datetime to UTC:
(note: in this example self.start_date is a fields.Date)
start_date = fields.Datetime.to_string(pytz.timezone(self.env.context['tz']).localize(fields.Datetime.from_string(self.start_date), is_dst=None).astimezone(pytz.utc))
similar but with +24 hrs
end_date = fields.Datetime.to_string(pytz.timezone(self.env.context['tz']).localize(fields.Datetime.from_string(self.end_date), is_dst=None).astimezone(pytz.utc) + timedelta(hours=24))
This was used because the passed values (self.start_date) were field.Date and therefor did not get affected by timezones, while the target stored fields were fields.Datetime and therefor stored in UTC.
start_date/end_date which are now in UTC can then be used in a self.env[''].search([])

Converting time stamp to minutes elapsed in Python

I am making a news blog for my project in which I have to display time under the news title as x minutes ago etc.
From the RSS feed of the news, I have the time stamp in the form of a string. For example:
timestamp = 'Tue, 12 Feb 2013 07:43:09 GMT'
I am trying to find the difference between this timestamp and the present time using datetime module in python. But for some reason it gives error:
ValueError: astimezone() cannot be applied to a naive datetime
I'll appreciate if somebody can point me in the right direction. Below is my attempt in Python:
from datetime import datetime
from pytz import timezone
timestamp = 'Tue, 12 Feb 2013 07:43:09 GMT'
t = datetime.strptime(timestamp, '%a, %d %b %Y %I:%M:%S %Z')
now_time = datetime.now(timezone('US/Pacific'))
# converting the timestamp to Pacific time
t_pacific = t.astimezone(timezone('US/Pacific')) # get error here
diff = t_pacific - t
Thanks!
Prakhar
Your example had a few problems (I see you've fixed them now):
First line should be:
from datetime import datetime
It looks as though you're missing a closing parenthesis on the 4th line:
now_time = datetime.now(timezone('US/Pacific')
What is timezone()? Where does that come from?
You don't really need to mess with timezones, I don't think — just use GMT (UTC). How about something more like this:
from datetime import datetime
timestamp = 'Tue, 12 Feb 2013 07:43:09 GMT'
t = datetime.strptime(timestamp, '%a, %d %b %Y %I:%M:%S %Z')
t_now = datetime.utcnow()
diff = t_now - t
The problem here is that t does not have a timezone—that's what the error message means by "naive datetime". From the docs:
There are two kinds of date and time objects: “naive” and “aware”… An aware object has sufficient knowledge of… time zone and daylight savings time information… A naive object does not…
You can verify that it's naive by doing this:
print(t.tzinfo)
The answer will be None.
As the astimezone docs say:
self must be aware (self.tzinfo must not be None, and self.utcoffset() must not return None).
The strptime function always generates a naive datetime.
You can fix this in various ways:
First convert t to a GMT datetime instead of a naive one, and then your conversion to 'US/Pacific' will work.
As the docs say, "If you merely want to attach a time zone object tz to a datetime dt without adjustment of date and time data, use dt.replace(tzinfo=tz)." Since you know the time is in UTC, just replace the empty tz with UTC, and you've got an aware time.
Convert to PST with a different mechanism than astimezone, on which will assume UTC or which allows you to specify the source.
There are various alternatives out there, but you're already using pytz, so see its documentation.
Convert now_time to UTC instead of converting t to PST.
The last one is probably the simplest and best for most use cases. Since you've only got now_time in PST because you explicitly asked for it that way, all you have to do is not do that (or explicitly ask for 'GMT' instead of 'US/Pacific'). Then you can just do your date arithmetic on UTC times.
If you need to display final results in PST, it's still often better to do the arithmetic in UTC, and convert at the end. (For example, you can have two times that are an hour apart, but have the same value in Pacific, because of 1am on DST day being repeated twice; that won't be an issue if you stay in UTC all the time.)

Categories