This is not the first time Obama has come out in favor of gay marriage. He borrowed from the playbook of a famous flip-flopper, John Kerry, but not to be outdone by Kerry, he was for it before he was against it before he was for it again. The whole episode is merely one more divisive issue to exploit during an election year.
In 1996, Obama was in favor of gay marriage and would fight any efforts to prohibit it. 
Then he flipped. In 2004  and 2008  his position was for civil unions instead; that as a Christian he believes marriage is a sacred union between a man and a woman; that gay marriage is not a civil right. This is essentially the same position as Mitt Romney.
Then he waffled. In 2010  Obama was "struggling" (a trial balloon?) and then he finally flipped again recently in favor of gay marriage.
Why the flip flops? Call me a cynic, but ...
1996: He ran for the Illinois State Senate from a liberal district.
2004: He ran for the U.S. Senate and needed to appeal to a larger audience.
2008: He ran for President and needed to appeal to a larger audience.
2010: His popularity plummeted (even within his base).
2012: He's running for a 2nd term, the economy and public finances are a shambles.
And in the first 90 minutes after the news broke Wednesday, his campaign received $1 million in "spontaneous" contributions from pro-gay PACs ... so that doesn't hurt either. Flip-flopping apparently pays off. 
Obama is also borrowing from the Republican play book by focusing on divisive social issues. God forbid we have that important conversation about declining incomes, unemployment, deficit spending, unfunded entitlements, the parabolic rise in the national debt, war without end and the fiscal cliff at the end of the year.  The whole strategy is to divide people and play them against each other to keep them distracted from the broader issues. That's how politicians (as opposed to statesmen) get elected.
For what it’s worth, 17 states recognize same-sex unions and 31 states have voted down same-sex legislation by referendum. Marriage has always been an issue handled by the states and there is nothing in the U.S. Constitution that grants the Federal Government power to regulate it. If a state wants to legalize same-sex unions or ban them, the Feds should stay the hell out of it. Using Federal power to force social issues only polarizes us as a nation.
 2004, Obama says marriage (gay or otherwise) is not a civil right: YouTube
 2008, Obama says marriage is a sacred union between a man and a woman: YouTube
 Obama says he’s struggling with the issue, supports separate but equal for civil unions: YouTube
 Gay donors reportedly constitute 1 in 6 of Obama’s top PAC contributors: Washington Post
 The 2013 Fiscal Cliff Could Crush Stocks (and the economy): Wall Street Journal