How can I format a datetime string like 2020-04-30T22:30:00-04:00 to something like 2015-03-22T10:00:00+0900 in Python? The formatting, not the actual date.
The 2 examples you have provided don't appear to have different formatting,
they're both ISO8601 Extended format.
If you need to specify your own format you can use the datetime function strftime and a format string, the reverse of this is strptime, which takes an input string and a format string and returns a datetime object
If you need to change timezones then the tzinfo object what your looking for
You might also be interested in the dateutil
Computing of relative deltas (next month, next year, next Monday, last week of month, etc);
Computing of relative deltas between two given date and/or datetime objects;
Computing of dates based on very flexible recurrence rules, using a superset of the iCalendar specification.
Parsing of RFC strings is supported as well. Generic parsing of dates in almost any string format
Timezone (tzinfo) implementations for tzfile(5) format files (/etc/localtime,/usr/share/zoneinfo, etc), TZ environment string (in all known
formats), iCalendar format files, given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, UTC timezone, and Windows registry-based time zones. Internal up-to-date world timezone information based on Olson’s database.
Computing of Easter Sunday dates for any given year, using Western, Orthodox or Julian algorithms
Related
The datetime module allows for returning an integer representation of the weekday with:
weekday = dt.date.today().weekday()
However, this seems to be in UTC timezone (the default timezone for datetime). How can I convert this weekday integer to be adjusted for a timezone such as GMT? What I am looking for is something like the following using the pytz module:
weekday = dt.date.today().astimezone(pytz.gmt).weekday()
Is there an easy method of doing this so that the day reporting is accurate based on the shift in hours from the timezone? Thanks for any/all information.
I have a column of float values which are tweet creation dates. This is the code I used to convert them from float to datetime:
t = 1508054212.0
datetime.utcfromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
All the values returned belong to October 2017. However, the data is supposed to be collected over multiple months. So the dates should have different months and not just different Hours, Minutes and Seconds.
These are some values which I need to convert:
1508054212.0
1508038548.0
1506890436.0
Request you to suggest an alternative approach to determine the dates. Thank you.
I assumed df['tweet_creation'].loc[1] will return a number like the examples you gave.
Unfortunately, I don't know what f is, but I assumed it was a float.
My answer is inspired by this other answer: Converting unix timestamp string to readable date. You have a UNIX timestamp, so the easiest way is to use it and not convert it as a string.
from datetime import datetime, timedelta
dtobj = datetime.utcfromtimestamp(int(df['tweet_creation'].loc[1])) + timedelta(days=f-int(f))
To have the string representation you can use the function strftime.
I have this timestamp value being return by a web service "2014-09-12T19:34:29Z"
I know that it means timezone, but what exactly does it mean?
And I am trying to mock this web service, so is there a way to generate this timestamp using strftime in python?
Sorry if this is painfully obvious, but Google was not very helpful and neither was the strftime() reference page.
I am currently using this :
x.strftime("%Y-%m-%dT%H:%M:%S%Z")
'2015-03-26T10:58:51'
The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.
I am currently battling the cruel beast that is timezone localization in my django application, and having some trouble... I want to make naive datetimes timezone aware, based on a location. I have a database of zip codes that have the UTC offset in hours, as well as a 0 or 1 depending on if the zip codes adhere to DST. How might I use this data to accurately apply a timezone to my datetimes? Ideally the datetime would respond to changes in DST, rather than just always simply following the UTC offset.
With pytz it's not hard to convert the datetimes as you describe; the only complication is getting tzinfo instances corresponding to the time zone descriptions in your database.
The problem is that real timezones are more complicated than just offset + DST. For example, different regions adopted DST at different points in history, and different regions in the world can make the DST switch at different points in the year.
If your usage is only for the US, and only concerns future (not historical) dates, then there are a couple options that should yield accurate results (though note the caveat below):
Just create your own concrete tzinfo subclass that uses the offset and DST flag from your database. For example, the Python documentation gives sample code for "a complete implementation of current DST rules for major US time zones."
Map from the offset / DST to the corresponding pytz tzinfo object. Since there are only a handful of possible combinations in the US, just figure out which timezone name corresponds and use that.
TZ_MAP = {
...
(-5, 1): pytz.timezone('US/Eastern')
...
}
tz = TZ_MAP[(offset, is_dst)]
Once you have the tzinfo instance the conversion is simple, but note that dealing with DST involves inherent ambiguities. For example, when the clock is turned back at 2am, all the times between 1am and 2am occur twice in the local timezone. Assuming you don't know which one you actually mean, you can either pick one arbitrarily, or raise an exception.
# with no is_dst argument, pytz will guess if there is ambiguity
aware_dt = tz.localize(naive_dst)
# with is_dst=None, pytz will raise an exception if there is ambiguity
aware_dt = tz.localize(naive_dst, is_dst=None)
I would like a simple way to find and reformat text of the format 'DD/MM/YYYY' into 'YYYY/MM/DD' to be compatible with MySQL TIMESTAMPs, in a list of text items that may or may not contain a date atall, under python. (I'm thinking RegEx?)
Basically i am looking for a way to inspect a list of items and correct any timestamp formats found.
Great thing about standards is that there are so many to choose from....
You can read the string into a datetime object and then output it back as a string using a different format. For e.g.
>>> from datetime import datetime
>>> datetime.strptime("31/12/2009", "%d/%m/%Y").strftime("%Y/%m/%d")
'2009/12/31'
Basically i am looking for a way to inspect a list of items and correct any timestamp formats found.
If the input format is inconsistent, can vary, then you are better off with dateutil.
>>> from dateutil.parser import parse
>>> parse("31/12/2009").strftime("%Y/%m/%d")
'2009/12/31'
Dateutil can handle a lot of input formats automatically. To operate on a list you can map the a wrapper over the parse function over the list and convert the values appropriately.
If you're using the MySQLdb (also known as "mysql-python") module, for any datetime or timestamp field you can provide a datetime type instead of a string. This is the type that is returned, also and is the preferred way to provide the value.
For Python 2.5 and above, you can do:
from datetime import datetime
value = datetime.strptime(somestring, "%d/%m/%Y")
For older versions of python, it's a bit more verbose, but not really a big issue.
import time
from datetime import datetime
timetuple = time.strptime(somestring, "%d/%m/%Y")
value = datetime(*timetuple[:6])
The various format-strings are taken directly from what's accepted by your C library. Look up man strptime on unix to find other acceptable format values. Not all of the time formats are portable, but most of the basic ones are.
Note datetime values can contain timezones. I do not believe MySQL knows exactly what to do with these, though. The datetimes I make above are usually considered as "naive" datetimes. If timezones are important, consider something like the pytz library.