Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strptime with Timezone

Tags:

I have a String which I parse with DateTime.strptime. The Timezone of the Date in the String is CET but Ruby creates an UTC DateTime object which of course has an offset of 2hrs.

Currently I'm working around the issue with DateTime.strptime().change(:offset => "+0020") but I'm pretty sure this is not the way it's meant to work.

Can someone enlighten me on the correct way to do this?

like image 429
Nicolas Avatar asked Oct 26 '11 21:10

Nicolas


People also ask

What is the Strptime format?

The strptime() function in Python is used to format and return a string representation of date and time. It takes in the date, time, or both as an input, and parses it according to the directives given to it. It raises ValueError if the string cannot be formatted according to the provided directives.

What does datetime datetime Strptime do?

Python DateTime – strptime() Function strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.

Which Python library is used for timezone?

pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference ( datetime. tzinfo ).

How do I print UTC time in Python?

datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC. Lastly, use the timestamp() to convert the datetime object, in UTC, to get the UTC timestamp.


1 Answers

I use it the following way:

ruby-1.9.2-head :001 > require 'date'  => true  ruby-1.9.2-head :002 > fmt = "%m-%d-%Y %H:%M:%S %Z"  => "%m-%d-%Y %H:%M:%S %Z"  ruby-1.9.2-head :003 > DateTime.strptime "10-26-2011 10:16:29 CET", fmt  => #<DateTime: 2011-10-26T10:16:29+01:00 (212186380589/86400,1/24,2299161)>  ruby-1.9.2-head :004 > DateTime.strptime "10-26-2011 10:16:29 UTC", fmt  => #<DateTime: 2011-10-26T10:16:29+00:00 (212186384189/86400,0/1,2299161)>  ruby-1.9.2-head :005 > DateTime.strptime "10-26-2011 10:16:29 PST", fmt  => #<DateTime: 2011-10-26T10:16:29-08:00 (212186412989/86400,-1/3,2299161)>  

Is it what you mean?

like image 198
WarHog Avatar answered Sep 18 '22 02:09

WarHog