Reputation: 1511
I am having timestamp fields in my JSON data where some of the timestamps have timestamp in this format str("2014-05-12 00:00:00")
and another in this format str("2015-01-20 08:28:16 UTC")
. I would like to get year, month, day fields only from the string. I have tried the following approach but not sure what is the problem. Can someone please correct me. I have searched some of the answers from StackOverflow but nothing helped me.
from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")
def convert_timestamp(date_timestamp=None):
if '%Z' in date_timestamp:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
else:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
print convert_timestamp(date_posted_zone)
Upvotes: 1
Views: 1059
Reputation: 267
from dateutil import parser
datetime_no_timezone = parser.parse("2015-01-20 08:28:16")
datetime_with_timezone = parser.parse("2015-01-20 08:28:16+02:00")
if datetime_no_timezone.tz == None:
# CODE ALWAYS GO THROUGH THIS
pass
if datetime_no_timezone.tz:
# CODE ALWAYS GO THROUGH THIS
pass
Upvotes: 0
Reputation: 26
I've tried following code to search timezone in str and its working.
from datetime import datetime
date_posted=str("2014-05-12 00:00:00")
date_posted_zone=str("2015-01-20 08:28:16 UTC")
zone=date_posted_zone.split(" ")
print(zone[2])
def convert_timestamp(date_timestamp=None):
if zone[2] in date_timestamp:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
else:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
print convert_timestamp(date_posted_zone)
Upvotes: 1
Reputation: 531390
You're checking if the literal string %Z
is in the timestamp value; only strptime
(and strftime
) can actually make use of the format character.
What you can do is simply try to parse the string as if it had a timezone, and if that fails, try to parse it without.
def convert_timestamp(date_timestamp=None):
try:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S %Z")
except ValueError:
d = datetime.strptime(date_timestamp, "%Y-%m-%d %H:%M:%S")
return d.strftime("%Y-%m-%d")
Of course, as written, you don't really need to parse the string at all; just split it on whitespace and return the first component. (Your existing code already assumes that the year/month/date matches.)
def convert_timestamp(date_timestamp):
return date_timestamp.split()[0]
Upvotes: 1